关于复选框绑定(bind)问题的几个答案,例如this one建议
<checkbox IsChecked="{Binding Path=MyProperty, Mode=TwoWay}"/>
应该可以。我在以下不起作用的代码中遗漏了什么?
<Window x:Class="TestBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<CheckBox Name="checkBox1" IsChecked="{Binding Path=MyProperty, Mode=TwoWay}">CheckBox</CheckBox>
</Grid>
</Window>
namespace TestBinding
{
public partial class Window1 : Window
{
bool property = true;
public Window1()
{
InitializeComponent();
}
public bool MyProperty
{
get
{
return property;
}
set
{
property = value;
}
}
}
}
更新
3 个很好的答案,非常感谢,我想全部接受,但接受了第一个提到 DataContext 的部分,这是我最感兴趣的影响绑定(bind)方向的部分。TwoWay 模式结果是一条红鲱鱼 感谢 MVVM 的建议,我正在使用它,但希望这段代码尽可能简单
最佳答案
您需要将 DataContext 设置为包含 xaml 绑定(bind)到的属性的对象。在您的情况下,只需将 Datacontext = this;
放在 c'tor 中。以及从每个绑定(bind)属性实现 INotifyPropertyChanged 接口(interface)和 RaisePropertyChange。
正如其他人所说,最好使用 MVVM 模式,在该模式中,您将属性存储在单独的类中,而不是隐藏在 UI 代码中。
关于c# - 为什么 wpf 复选框绑定(bind)可能无法工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8383373/