2016-03-24 11 views
1

こんにちは:)私は非常に基本的なアプリケーションでINotifyPropertyChangedの仕組みを理解しようとしています。私は単に私のmainWindowにボタンを持っていて、それを押すと、特定の属性にバインドされているtextBoxを更新するイベントを発生させるはずです。ただし、イベントが発生しても、常にnullになるため、textBoxは更新されません。INotifyPropertyChanged、イベントは常にnull

<Window x:Class="StockViewer.MainWindow" 
    <!--Just erased some basic xaml here--> 
    Title="MainWindow" Height="350" Width="525"> 
<Window.DataContext> 
    <local:RandomGen/> 
</Window.DataContext> 

<Grid> 
    <Button Click="incr" Height="30" VerticalAlignment="Top" Background="DarkGoldenrod"></Button> 
    <TextBlock VerticalAlignment="Top" Margin="40" Text="{Binding price, UpdateSourceTrigger=PropertyChanged}" Background="Aqua"></TextBlock> 
</Grid> 

ボタンを押すと、価格は変更する必要があります。

public partial class MainWindow : Window 
{ 
    private RandomGen gen; 
    public MainWindow() 
    { 
     gen = new RandomGen();   
     InitializeComponent(); 
    } 
    private void incr(object sender, RoutedEventArgs e) 
    { 
     gen.price = 7; 
    } 
} 

class RandomGen : NotifiedImp 
    { 
    public RandomGen() 
     { 
      _i = 3; 
     } 
     private int _i; 

     public int price 
     { 
      get { return _i; } 
      set 
      { 
       _i = value; 
       OnPropertyChanged("price"); 
      } 
     } 
    } 

class NotifiedImp: INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged;   
     protected void OnPropertyChanged([CallerMemberName] string propertyName = null) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
      { 
       handler(this,new PropertyChangedEventArgs(propertyName)); 
      } 
     } 
    } 

それは本当に奇妙だ、ハンドラは常にnullです。

<Window.DataContext> 
    <local:RandomGen/> 
</Window.DataContext> 

、別のは、あなたのMainWindowコンストラクタで初期化:あなたはあなたがRandomGenの2つのインスタンス、1があなたのXAMLで初期化を持って

+0

あなたは 'gen'に束縛していません。 –

答えて

2

:)をありがとうは、あなたがあなたのgen.price = 7;を更新するとき

gen = new RandomGen(); 

これは、あなたのDataContextであるインスタンスを更新していません。解決策のような

public MainWindow() 
{ 
    gen = new RandomGen();   
    InitializeComponent(); 
    DataContext = gen; 
} 

最もMVVM priceを更新するために、あなたのRandomGenオブジェクトにICommandを使用することです:そうは次のように

一つの解決策は、XAMLであなたの<Window.DataContext>設定を削除し、あなたのMainWindowコンストラクタでDataContextに設定されますイベントハンドラを使用するのではなく、XAMLで次のようにこのコマンドを使用します。

<Button Command="{Binding IncrementPriceCommand}"></Button> 

DataContextを初期化する場合は、RandomGenバッキングフィールドのいずれかを維持する必要はありません。

関連する問題