2013-02-19 12 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) –

+2

私はMSDNではなく別のソースを読み込んでいるので、私はdownvoteにはふさわしくないと思います... –

+2

@ofstream私はdownvoteをしませんでしたが、この質問は研究努力を示していないためです。この問題は非常に基本的なものであり、WPFのバインディングシステムを扱う人は、INotifyPropertyChangedを実装して、バインディングが変更されたときにバインディングを再評価するようにUIに通知する必要があることを知っています。バインディングを導入するほとんどすべての単一WPFチュートリアルでこの概念がカバーされています。 – Rachel

答えて

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

それは、ありがとう!私はあなたが私にできるときにあなたを受け入れるでしょう:) –

+0

短い、きれいで理解しやすい。ありがとう! – mcy

関連する問題