2014-03-26 50 views
3

我有一個名爲MyWindow.xaml XAML文件,而這個XAML宣佈爲複選框..不綁定複選框中的WPF器isChecked工作

<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; 

任何意見,將不勝感激。

+1

你設置的DataContext? – Maximus

+0

試過這樣嗎? (App.Current.MainWindow as MyWindow).IsChecked = true; – WPFUser

回答

1

您的觀點並沒有綁定到IsChkChecked因爲它沒有住在DataContext的。通常你會聲明一個ViewModel屬性,並聲明DataContext是這個ViewModel的一個實例。一個快速的解決將是改變視圖的構造到DataContext設置爲視圖本身或更改綁定(如dkozl的建議):

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

如果您在默認情況下未指定其他綁定源,它將在DataContext中搜索,我看不到您將它設置在任何位置。一種方法是設置RelativeSource對結合點Window一個發佈IsChkChecked財產

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