尽管缺乏 PropertyChanged 触发,数据绑定似乎仍然有效
我有一个窗口,其中有两个复选框绑定到类选项的属性:
public class Options
{
public bool Option1 { get; set; }
public bool Option2 { get; set; }
public bool AnotherOption { get; set; }
}
xaml:
<CheckBox
Content="Option #1"
IsChecked="{Binding Path=Option1}"/>
<CheckBox
Content="Option #2"
IsChecked="{Binding Path=Option2}"/>
此外,我还有第三个复选框,当其他两个复选框未选中时,应禁用该复选框。为了实现这一点,我使用了多重绑定:
<CheckBox
IsChecked="{Binding Path=AnotherOption}"
Content="Another option">
<CheckBox.IsEnabled>
<MultiBinding Converter="{StaticResource MultiValueLogicalOrConverter}">
<Binding Path="Option1"/>
<Binding Path="Option2"/>
</MultiBinding>
</CheckBox.IsEnabled>
</CheckBox>
转换器:
public class MultiValueLogicalOrConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.Cast<bool>().Any(value => value);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
这似乎工作正常。但有时有人指出 Option 的属性不是依赖属性,并且不会触发 PropertyChanged 事件,所以我无法解释为什么这是有效的。有什么想法吗?
I have a window with two checkboxes bound to properties of class Options:
public class Options
{
public bool Option1 { get; set; }
public bool Option2 { get; set; }
public bool AnotherOption { get; set; }
}
xaml:
<CheckBox
Content="Option #1"
IsChecked="{Binding Path=Option1}"/>
<CheckBox
Content="Option #2"
IsChecked="{Binding Path=Option2}"/>
Also I have third checkbox that should be disabled when the other two are unchecked. To achieve this I used multibinding:
<CheckBox
IsChecked="{Binding Path=AnotherOption}"
Content="Another option">
<CheckBox.IsEnabled>
<MultiBinding Converter="{StaticResource MultiValueLogicalOrConverter}">
<Binding Path="Option1"/>
<Binding Path="Option2"/>
</MultiBinding>
</CheckBox.IsEnabled>
</CheckBox>
converter:
public class MultiValueLogicalOrConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.Cast<bool>().Any(value => value);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
This seems to work fine. But sometime it was pointed out that Option's properties are not dependency properties and don't fire PropertyChanged event, so I cannot explain why this works. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不需要视图来关心模型,那么使用 INotify 接口就没有意义。但是,如果由于任何原因模型的属性发生了变化,如果您希望视图能够意识到这一点,则需要进行更改。
If you don't need the view to care about the model, then there's no point in using the INotify interface. However, if for any reason the model's property changes, you'll need to if you want your view to be aware of it.
当您使用 GUI 中的绑定更新模型时,绑定会重新加载模型以获取结果值。
When you update a model with a binding from the GUI, the model is reloaded by the bindings to get the result value.