2017-10-20 5 views
1

내 속성은 제대로 업데이트되지만 사용자 인터페이스는 업데이트되지 않습니다. 내가 뭘 잘못 했니?바운드 요소에 대한 UI가 업데이트되지 않습니다.

DataContext도 XAML이 아닌 코드 숨김 생성자에서 설정했지만 그 중 하나도 작동하지 않았습니다.

뷰 모델 :

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 "; 
    } 
} 

보기 : 당신은 제대로 PropertyChanged을 구현하지 않는

<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

. .NET 용 이벤트 모델은 호출 된 위임자의 sender 인수가 실제로 이벤트를 발생시킨 개체의 참조로 설정되어야합니다. 이 값을 null으로 설정합니다. 코드는 대신 this를 사용해야합니다 : 스레드 안전을 위해, 당신은 또한 이벤트 필드 자체에 "확인하고 인상"패턴을 사용하지 않도록

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

참고. 대신 로컬 변수에 필드를 저장하고 로컬 변수를 확인한 다음 null이 아닌 경우 해당 변수에서 이벤트를 발생시켜야합니다. ?. 연산자 ("null 조건부 연산자")를 사용하는 위의 경우 효과적으로이 작업을 수행합니다. 컴파일러는 암시 적으로 로컬 변수를 생성하고 null을 확인하는 시간과 실제로 사용하려고 시도한 시간 사이에 참조가 변경되지 않도록합니다.

+0

정말 고맙습니다. 내가 그것을 놓쳤다라고 생각할 수 없다 :) – Patrick

관련 문제