绑定不在Checkbox isChecked WPF中工作

时间:2014-03-26 10:45:35

标签: wpf binding

我有一个名为MyWindow.xaml的xaml文件,这个xaml有一个声明为..的复选框。

<CheckBox Name="chkView" IsChecked="{Binding Path=IsChkChecked, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"  Checked="chkView_Checked" Unchecked="chkView_Checked" />

在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));
    }

现在,Iam尝试从另一个类访问此属性并更改属性,但该复选框未绑定到bool属性。

MyLib.MyWindow wnd;
            wnd= (MyLib.MyWindow)theTabItem.Content;
                    wnd.IsChkChecked = true;

任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果您默认情况下未指定其他绑定源,则会在DataContext中搜索,但我无法看到您将其设置在任何位置。一种方法是将RelativeSource设置为绑定指向发布Window属性的IsChkChecked

<CheckBox Name="chkView" IsChecked="{Binding Path=IsChkChecked, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>

答案 1 :(得分:1)

您的视图不会绑定到IsChkChecked ,因为它不会存在于DataContext中。通常,您将使用该属性声明ViewModel,并将DataContext声明为此ViewModel的实例。快速解决方法是更改​​视图的构造函数以将DataContext设置为View本身或更改Binding(如dkozl建议的那样):

public MyWindow()
{
    InitializeComponent();
    this.DataContext = this;
}