绑定在复选框中不起作用 isChecked WPF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22658555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding not working in Checkbox isChecked WPF
提问by surajitk
I have a xaml file named MyWindow.xaml, and this xaml has a checkbox declared as..
我有一个名为 MyWindow.xaml 的 xaml 文件,这个 xaml 有一个复选框声明为..
<CheckBox Name="chkView" IsChecked="{Binding Path=IsChkChecked, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Checked="chkView_Checked" Unchecked="chkView_Checked" />
In MyWindow.xaml.cs,
在 MyWindow.xaml.cs 中,
public partial class MyWindow: UserControl,INotifyPropertyChanged
{
public MyWindow()
{
InitializeComponent();
}
private bool isChkChecked;
public bool IsChkChecked
{
get { return isChkChecked; }
set
{
isChkChecked= value;
OnPropertyChanged("IsChkChecked");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
Now, Iam trying to access this property from another class and change the property, but the checkbox is not getting binded to bool property.
现在,我试图从另一个类访问此属性并更改该属性,但复选框未绑定到 bool 属性。
MyLib.MyWindow wnd;
wnd= (MyLib.MyWindow)theTabItem.Content;
wnd.IsChkChecked = true;
Any suggestions would be appreciated.
任何建议,将不胜感激。
采纳答案by MatthiasG
Your view doesn't bind to IsChkChecked as it doesn't live in the DataContext. Usually you would declare a ViewModel with the property and declare the DataContext to be an instance of this ViewModel. A quick fix would be to change the constructor of the view to set the DataContext to the View itself or change the Binding (as dkozl suggested):
您的视图不会绑定到,IsChkChecked 因为它不在 DataContext 中。通常,您会使用该属性声明一个 ViewModel,并将 DataContext 声明为该 ViewModel 的一个实例。快速修复是更改视图的构造函数以将 DataContext 设置为视图本身或更改绑定(如 dkozl 建议的那样):
public MyWindow()
{
InitializeComponent();
this.DataContext = this;
}
回答by dkozl
If you don't specify another binding source by default it will search in DataContextand I cannot see that you set it anywhere. One way is to set RelativeSourceagainst binding to point to Windowthat publishes IsChkCheckedproperty
如果默认情况下您没有指定另一个绑定源,它将搜索DataContext并且我看不到您在任何地方设置了它。一种方法是将RelativeSource绑定设置为指向Window该发布IsChkChecked属性
<CheckBox Name="chkView" IsChecked="{Binding Path=IsChkChecked, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>

