2013-02-19 71 views
8

我有一個項目,我在該代碼隱藏中綁定複選框的IsChecked屬性和get/set。但是,當應用程序加載時,由於某種原因它不會更新。出於好奇,我剝離下來到它的基礎,就像這樣:WPF DataBinding不更新?

//using statements 
namespace NS 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     private bool _test; 
     public bool Test 
     { 
      get { Console.WriteLine("Accessed!"); return _test; } 
      set { Console.WriteLine("Changed!"); _test = value; } 
     } 
     public MainWindow() 
     { 
      InitializeComponent(); 
      Test = true; 
     } 
    } 
} 

XAML:

<Window x:Class="TheTestingProject_WPF_.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
<Grid> 
    <Viewbox> 
     <CheckBox IsChecked="{Binding Path=Test, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> 
    </Viewbox> 
</Grid> 

而且,你瞧,當我把它設置爲true,它沒有更新!

任何人都可以想出一個修復,或解釋爲什麼?

謝謝,這將不勝感激。

+0

閱讀[介紹材料](http://msdn.microsoft.com/en-us/library/ms752347.aspx)。 – 2013-02-19 19:38:39

+2

我不認爲我值得downvote,因爲我讀了另一個來源,而不是MSDN ... – 2013-02-19 19:40:17

+2

@ofstream我沒有downvote,但我懷疑這是因爲這個問題沒有顯示任何研究工作。這個問題是非常基本的,任何使用WPF綁定系統的人都知道,你需要實現'INotifyPropertyChanged'來讓你的屬性通知UI來重新評估綁定。幾乎每一個介紹綁定的WPF教程都涵蓋了這個概念。 – Rachel 2013-02-19 19:44:28

回答

22

爲了支持數據綁定,數據對象必須實現INotifyPropertyChanged

而且,它總是一個好主意,Separate Data from Presentation

public class ViewModel: INotifyPropertyChanged 
{ 
    private bool _test; 
    public bool Test 
    { get { return _test; } 
     set 
     { 
      _test = value; 
      NotifyPropertyChanged("Test"); 
     } 
    } 

    public PropertyChangedEventHandler PropertyChanged; 

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

<Window x:Class="TheTestingProject_WPF_.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <Viewbox> 
     <CheckBox IsChecked="{Binding Path=Test, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> 
    </Viewbox> 
</Grid> 

代碼背後:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     DataContext = new ViewModel{Test = true}; 
    } 
} 
+0

工作,謝謝!我會接受你,當它讓我:) – 2013-02-19 19:43:18

+0

簡短,乾淨,容易理解。謝謝! – mcy 2013-11-08 12:35:24