2016-07-13 9 views
0

私はPrism Frameworkを使用してMVVMアプリケーションを作成しています。プロパティ値が変更されたときにラベルを更新することはできません。モデルを作成してプロパティに初期値を割り当てると、それにバインドされているlableが更新されます。しかし、アプリケーションの存続期間中にプロパティを変更すると、ラベルは内容を更新しません。ここでバインドされたVMプロパティの変更時にWPF MVVMコントロールが更新されない

は私のXAMLである:ここでは

<Window x:Class="Project.Views.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="700" Width="700"> 
    <DockPanel LastChildFill="True"> 
      <Button x:Name="btnStart" Command="{Binding Path=Start}" Content="StartProcess"/> 

      <GroupBox Header="Current Operation"> 
       <Label x:Name="lblCurrentOperation" Content="{ Binding CurrentOperationLabel, UpdateSourceTrigger=PropertyChanged}"/> 
      </GroupBox> 
    </DockPanel> 
</Window> 

は私のViewModelです:

public class MyModelViewModel : BindableBase 
{ 
    private MyModel model; 
    private string currentOpeartion; 

    public DelegateCommand Start { get; private set; } 

    public string CurrentOperationLabel 
    { 
     get { return currentOpeartion; } 
     set { SetProperty(ref currentOpeartion, value); } 
    } 

    public MyModelViewModel() 
    { 
     model = new MyModel(); 

     Start = new DelegateCommand (model.Start); 
     CurrentOperationLabel = model.CurrentOperation; //Bind model to the ViewModel 
    } 
} 

そして、私のモデルでは、 "スタート" コマンドが呼び出されたとき、私はラベルを変更します。

public class MyModel 
{ 
    public string CurrentOperation { get; set; } 

    public MyModel() 
    { 
     CurrentOperation = "aaa"; //This will make the label show "aaa" 
    } 

    public void Start() 
    { 
     CurrentOperation = "new label"; //This should alter the Label in the view, but it doesn't 
    } 
} 
+1

あなたが表示しているコードは、INotifyPropertyChangedを実装していません。これは提供されていないと仮定しています。BindableBaseでコードを追加できますか? – MikeT

+0

モデルクラスの 'Start()'メソッドを呼び出して、新しい値 'new label'が来るかどうかを調べるときに、 'CurrentOperationLabel'のsetterでブレークポイントを設定しようとしました。 – StepUp

+0

私の最初の疑念は、あなたの開始メソッドがモデルをviewModelでなく変更してViewモデルがその変更を知らないので通知できないことです。 – MikeT

答えて

5

問題がStart方法では、モデル(すなわちCurrentOperation)としないビューモデル(すなわち、CurrentOperationLabel)のプロパティのプロパティを変更することです。 XAMLは、モデルがビューモデルにバインドされているため、モデルについては何も認識していません。つまり、MyModel.CurrentOperationプロパティを変更すると、XAMLはこの事実について通知されません。

この問題を解決するには、コードの構造を変更する必要があります。モデルを更新した後、ビューモデルを更新する必要があります。私の提案は、このようにMyModelViewModelを変更することです:

public class MyModelViewModel : BindableBase 
{ 
     //... 

     public void InnerStart() 
     { 
      model.Start(); 
      //Refresh the view model from the model 
     } 

     public MyModelViewModel() 
     { 
     model = new MyModel(); 

     Start = InnerStart; 
     CurrentOperationLabel = model.CurrentOperation; 
    } 
} 

アイデアは、ボタンのクリックは、モデルとの通信を担当してビューモデルで扱われるべきであるということです。さらに、モデルの現在の状態に基づいてプロパティを更新します。

+0

はい、あなたはポイントがあります。 ViewModelにそのモデルのプロパティが変更されたことをどのように通知する必要がありますか?あなたが私のコードを修正した場合、私は気にしません:) – Zwierzak

関連する問題