2017-10-20 7 views
1

プロパティは正常に更新されますが、ユーザーインターフェイスは更新されません。 何が間違っていますか?バインドされた要素のUIが更新されていません

DataContextをXAMLではなくコードビハインドコンストラクタに設定しようとしましたが、どちらも動作しませんでした。

のViewModel:

public class MainWindowViewModel : INotifyPropertyChanged 
{ 
    public MainWindowViewModel() 
    { 
     TestCommand = new RelayCommand(UpdateTest); 
    } 

    #region INotifyPropertyChanged 
    public event PropertyChangedEventHandler PropertyChanged; 


    protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(null, new PropertyChangedEventArgs(propertyName)); 
    } 
    #endregion 

    private string _test; 
    public string Test 
    { 
     get { return _test; } 
     set 
     { 
      _test = value; 
      NotifyPropertyChanged(); 
     } 
    } 

    public ICommand TestCommand { get; set; } 

    public void UpdateTest() 
    { 
     Test += "test "; 
    } 
} 

ビュー:

<Window x:Class="Test.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:Test" 
    Title="MainWindow" Height="350" Width="525"> 
    <Window.DataContext> 
     <local:MainWindowViewModel /> 
    </Window.DataContext> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="*" /> 
      <RowDefinition Height="*" /> 
     </Grid.RowDefinitions> 
     <TextBox Grid.Row="0" Text="{Binding Test}" /> 
     <Button Grid.Row="1" Content="Test 2" Command="{Binding TestCommand}" /> 
    </Grid> 
</Window> 

答えて

3

あなたは正しくPropertyChangedを実装していません。 .NETのイベントモデルでは、呼び出されたデリゲートの引数senderが実際にイベントを発生させるオブジェクトの参照に設定されている必要があります。その値をnullに設定します。あなたのコードではなくthisを使用する必要があります。スレッドの安全性のために、あなたもイベントフィールド自体の「チェックして上げる」パターンを使用してはならないこと

protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null) 
{ 
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
} 

注意を。代わりに、ローカル変数にフィールドを格納し、ローカル変数を確認してから、null以外の場合はその変数からイベントを発生させる必要があります。上記は、?.演算子( "null条件演算子")を使用して効果的にこれを行います。コンパイラは暗黙的にローカル変数を生成し、nullをチェックしてから実際に使用しようとしたときに参照が変更されないようにします。

+0

本当にありがとうございました。私はそれを逃したと信じられない:) – Patrick

関連する問題