2012-04-28 227 views
1

我簡單例子:WPF綁定不起作用

XAML:

<CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" Name="cb" /> 
<Button Name="button1" Click="button1_Click" /> 

後面的代碼:

public partial class MainWindow : Window 
{ 
    private ObservableCollection<MyObject> collection = new ObservableCollection<MyObject>(); 

    public MainWindow() 
    { 
     InitializeComponent(); 

     collection.Add(new MyObject(true)); 
     //grid.DataContext = collection[0]; 
    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     collection[0].IsSelected = false; 
    } 
} 

public class MyObject 
{ 
    public bool IsSelected { get; set; } 

    public MyObject(bool isSelected) 
    { 
     this.IsSelected = isSelected; 
    } 
} 

的cb.IsChecked不通過點擊按鈕雖然改變集合[0] .IsSelected已更改。

即使我取消註釋grid.DataContext =集合[0]; - 沒有改變。

在實際的例子中,我在列表框的項目模板中有相同的複選框。所以行爲是一樣的 - 複選框的選擇不會改變。

回答

3

您需要實現您的MyObject類型INotifyPropertyChanged的

2

請嘗試以下代碼:

public class MyObject : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    private void NotifyPropertyChanged(string info) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(info)); 
     } 
    } 

    private bool _isSelected; 

    public bool IsSelected 
    { 
     get { return _isSelected; } 
     set 
     { 
      _isSelected = value; 
      NotifyPropertyChanged("IsSelected"); 
     } 
    } 

    public MyObject(bool isSelected) 
    { 
     this.IsSelected = isSelected; 
    } 
}