2013-10-30 87 views
0

我嘗試使一個簡單的工作起作用,也就是在綁定到按鈕的Command所調用的方法中設置屬性時,出現了令人驚訝的困難。當在命令中設置屬性時,綁定不會更新

當我在ViewModel構造函數中設置屬性時,正確的值在View中正確顯示,但是當我使用該命令的方法設置該屬性時,View不會更新,儘管我創建的任何斷點都達到在我的ViewModelBase中的RaisePropertyChanged內)。我正在使用在線教程(如果沒有錯誤的話,來自Josh Smith)很容易找到的vanilla RelayCommand

我的項目可以下載here(Dropbox);

一些重要的代碼塊如下:

視圖模型:

public class IdiomaViewModel : ViewModelBase 
{ 

    public String Idioma { 
     get { return _idioma; } 
     set { 
      _idioma = value; 
      RaisePropertyChanged(() => Idioma); 
     } 
    } 
    String _idioma; 



    public IdiomaViewModel() { 
     Idioma = "nenhum"; 
    } 


    public void Portugues() { 
     Idioma = "portu"; 
    } 
    private bool PodePortugues() 
    { 
     if (true) // <-- incluir teste aqui!!! 
      return true; 
     return false; 
    } 
    RelayCommand _comando_portugues; 
    public ICommand ComandoPortugues { 
     get { 
      if (_comando_portugues == null) { 
       _comando_portugues = new RelayCommand(param => Portugues(), 
               param => PodePortugues()); 
      } 
      return _comando_portugues; 
     } 
    } 



    public void Ingles() { 
     Idioma = "ingle"; 
    } 
    private bool PodeIngles() 
    { 
     if (true) // <-- incluir teste aqui!!! 
      return true; 
     return false; 
    } 
    RelayCommand _comando_ingles; 
    public ICommand ComandoIngles { 
     get { 
      if (_comando_ingles == null) { 
       _comando_ingles = new RelayCommand(param => Ingles(), 
               param => PodeIngles()); 
      } 
      return _comando_ingles; 
     } 
    } 

} 

查看與背後並沒有額外的代碼:

<Window x:Class="TemQueFuncionar.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:app="clr-namespace:TemQueFuncionar" 
     Title="MainWindow" Height="350" Width="525"> 

    <Window.DataContext> 
     <app:IdiomaViewModel/> 
    </Window.DataContext> 

    <StackPanel> 
     <Button Content="Ingles" Command="{Binding ComandoIngles, Mode=OneWay}"/> 
     <Button Content="Portugues" Command="{Binding ComandoPortugues, Mode=OneWay}"/> 
     <Label Content="{Binding Idioma}"/> 

    </StackPanel> 
</Window> 

回答

1

Youdid填補接口實現把你沒有把它提起來基本視圖模型。 你錯過了這個: INotifyPropertyChanged連接接口到基類,這使得視圖刷新內容。

+0

只有一個問題:這是否意味着,即使當我實現預期的方法,我必須明確地說,我的類實現了接口本身? – heltonbiker

+0

確切地說,View會查找接口的存在,鉤子。與IDataValidator等一樣 – HichemSeeSharp

1

你錯過了聲明ViewModelBase:INotifyPropertyChanged的上ViewModelBase

相關問題