Windows phone 7 如何在UserControl中的复选框和更大范围内的ViewModel之间双向绑定?
我有一个Windows phone 7 如何在UserControl中的复选框和更大范围内的ViewModel之间双向绑定?,windows-phone-7,xaml,binding,user-controls,Windows Phone 7,Xaml,Binding,User Controls,我有一个UserControl,上面有一个复选框。当我使用主XAML页面上的UserControl时,我希望将控件上的属性双向绑定到ViewModel上的属性,例如 <myUserControl BtnIsBlacklisted="{Binding IsBlacklisted, Mode=TwoWay}" /> 我的UserControl复选框中有此项 <CheckBox x:Name="myCheckBox" ... IsChecked="{Binding Pat
UserControl
,上面有一个复选框。当我使用主XAML页面上的UserControl
时,我希望将控件上的属性双向绑定到ViewModel上的属性,例如
<myUserControl BtnIsBlacklisted="{Binding IsBlacklisted, Mode=TwoWay}" />
我的UserControl复选框中有此项
<CheckBox x:Name="myCheckBox"
...
IsChecked="{Binding Path=BtnIsBlacklisted,
ElementName=UserControl,
Converter={StaticResource BoolToNotBool},
Mode=TwoWay}" />
BlacklistedRetailers
更改的唯一方法是通过上面的set方法,因此无需从那里触发NotifyPropertyChanged
我在其他问题中尝试了许多建议,例如:
使用依赖项属性
包括Mode=TwoWay
使用包含网格上的自引用DataContext集绑定UserControl
(这也不起作用)
然而,这些都不起作用
最后的一些注意事项:
- 这是针对Windows Phone 7.5项目的
- Edit:单向绑定也不起作用,似乎绑定到
UserControl
自身属性时出现问题
一个元素名称绑定
与x:Name
值匹配,该值与设置绑定的元素在相同的名称范围内。显示的代码不够多,但您使用的是“UserControl”,我猜它没有设置为元素的名称,而是用于尝试匹配类型。如果在模板中声明了复选框
,则元素名称
也可能无法解析。您的BoolToNotBool
转换器也是双向的吗?是的。我现在对它做了更多的工作,我发现如果我直接从UserControl XAML绑定,而不是通过绑定,它就会工作。UserControl属性,例如IsChecked=“{Binding isblacklist,Converter={StaticResource BoolToNotBool},Mode=TwoWay}”
但是这不是很一般,因为它需要知道UserControl
中外部视图模型的名称。。。我还发现单向绑定无法正常工作,仅更新属性是因为我在DependencyPropertyChanged事件处理程序中设置了它们-问题已更新…明白了,我设置了x:Name=“thisUserControl”
在打开的UserControl
元素中,并在绑定中将其称为ElementName=thisUserControl
,它可以工作。谢谢
<CheckBox x:Name="myCheckBox"
...
IsChecked="{Binding Path=BtnIsBlacklisted,
ElementName=UserControl,
Converter={StaticResource BoolToNotBool},
Mode=TwoWay}" />
public bool IsBlacklisted
{
get
{
return App.VM.BlacklistedRetailers.Contains(this.Retailer);
}
set
{
if (value)
{
App.VM.BlacklistedRetailers.Add(this.Retailer);
}
else
{
while (App.VM.BlacklistedRetailers.Contains(this.Retailer))
{
App.VM.BlacklistedRetailers.Remove(this.Retailer);
}
}
this.NotifyPropertyChanged("IsBlacklisted");
}
}