2016-05-11 5 views
0

私は少し失われています、私のコードの文字列に自分のGUI上のラベルをバインドしようとしていますが、私のMainWindow()ブロックと私はどこからでもそれを更新することはできません。データバインディングはMainWindow()でのみ動作するようですWPF

これは私のINotifyPropertyChangedのクラスです:

 public class MyClass : INotifyPropertyChanged 
    { 
     private string _testLabel; 

     protected void OnPropertyChanged(PropertyChangedEventArgs e) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
       handler(this, e); 
     } 

     protected void OnPropertyChanged(string propertyName) 
     { 
      OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); 
     } 

     public string testLabel 
     { 
      get { return _testLabel; } 
      set 
      { 
       if (value != _testLabel) 
       { 
        _testLabel = value; 
        OnPropertyChanged("testLabelChanged"); 
       } 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 
    } 

これは、メインウィンドウ()ブロックである:

 public MainWindow() 
    { 
     InitializeComponent(); 
     testLabelName.DataContext = t; 
     t.testLabel = "Hello World 32432"; 
    } 

私も、この外側を宣言した:

MyClass t = new MyClass(); 

これは、私のXAMLのスニペット:

<Label Name="testLabelName" Content="{Binding Path=testLabel, Mode=OneWay}" Height="28" Margin="0,0,12,29" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="128" /> 

ラベルを設定するためにボタンイベントを使用してテストしましたが、設定されているようですが、GUIに変更はありません。私はGUIがPropertyChangedイベントで更新されていないと思っています。これは正しいですか?

おかげで、

答えて

2

私はあなたのコードの小さな問題があると思います。 PropertyChangedイベントを発生させるときは、プロパティの名前を指定する必要があります。プロパティのあなたのコードは次のようになります。あなたがプロパティの正しい名前を指定しない限り

public string testLabel 
    { 
     get { return _testLabel; } 
     set 
     { 
      if (value != _testLabel) 
      { 
       _testLabel = value; 
       OnPropertyChanged("testLabel"); // not testLabelChanged 
      } 
     } 
    } 

は、UWPはUIを更新しませんので、実際に変更されたプロパティを知る方法がない、と。

+0

あなたは素晴らしいです。ありがとうございました! –

+0

今後のタイプミスを避ける最も簡単な方法は、C#6の 'OnPropertyChanged(nameof(testLabel))'の機能を使うことです。 – ghord

0

変更してください:

OnPropertyChanged("testLabelChanged"); 

をする:

OnPropertyChanged("testLabel"); 
関連する問題