2017-11-10 26 views
1

現在、Fodyプロパティを使用してMVVMを使用してWPFプロジェクトを作成しようとしています。 PropertyChangedが期待通りに動作しない

public static class Model 
{ 
    public static string text { get; set; } 
} 

public class MainWindowViewModel : INotifyPropertyChanged 
{ 

    public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { }; 

    public static MainWindowViewModel Instance => new MainWindowViewModel(); 

    public string Text { get; set; } 
    /* 
    { 
     get { return Model.text; } 
     set 
     { 
      if (value == Text) 
       return; 

      Model.text = value; 

      PropertyChanged(this, new PropertyChangedEventArgs("Text")); 
     } 
    }*/ 

    public ICommand WSDLBrowseClick { get; set; } 


    public MainWindowViewModel() 
    { 
     WSDLBrowseClick = new RelayCommand(BrowseWSDL); 
    } 


    private void BrowseWSDL() 
    { 
     Text = "Test";   
    } 
} 

<Window x:Class="TestMVVM.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:local="clr-namespace:TestMVVM" 
    mc:Ignorable="d" 
    Title="MainWindow" Height="350" Width="525" 
    DataContext="{x:Static local:MainWindowViewModel.Instance}" 
    x:Name="WindowElement"> 

<StackPanel Orientation="Horizontal">   
    <TextBlock Text="{Binding Text, Mode=TwoWay}" /> 
    <Button Content="Browse" Command="{Binding WSDLBrowseClick}"/> 
</StackPanel> 

は基本的に私は、私はボタンをクリックしたときのTextBlockは、 "テスト" -Textを示したいと思います。 Click-Commandは実行されますが、TextBlockのテキストは変更されません。 TextBoxを最新の状態に保つローカルメモリとしてTextプロパティを使用して、後で値をmodel.textに送信してそこで使用できるようにします。しかし、私が現在コメントしているコードを使用する場合にのみ機能します。 fody weaverが私のために同じことをやろうとしているのではないのですか?(単にmodel.textを使う代わりに、別のprivate変数を作成するだけです)?

+0

FodyWeavers.xmlにウィーバーを追加しましたか?また、PropertyChangedEventに空のガードデリゲートを置かずに試してみてください.Fodyがそれを上書きしたくないかもしれません。 – Lennart

+0

あなたのコードはFodyのバージョン2.1.4を使ってうまく動作します。 – mm8

答えて

0

FodyWeavers.xmlに<PropertyChanged/>を追加して動作させることができました。

0

この例でわかるように、[ImplementPropertyChanged]属性でクラスをマークする必要があります。

Source

+0

この属性は現在は廃止されており、クラスにINotifyPropertyChangedを実装するだけで十分です – Lennart

0

あなたのテキストは、まったく変更されているので、ビューは何の手掛かりを持っていない新たな価値があることを通知されていないようです!

このコードを試してみてくださいテキスト変数セッターの代わりに(プロパティと完全には、あなたの正気のためのロジックを変更):

public string Text 
    { 
     get => _text; 
     set 
     { 
      OnPropertyChanged(nameof(Text)); 
      _text = value; 
     } 
    } 
    private string _text; 
    public event PropertyChangedEventHandler PropertyChanged; 
    [NotifyPropertyChangedInvocator] 
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
    } 

PLUSあなたが言うためにあなたのXAMLのセクションを更新する必要があります。

<TextBlock Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 
関連する問題