前提
仕事で使用しているC#のWPFの勉強の際に問題に直面したので質問させていただきます。
実現したいこと
実現したいことはボタンをクリック後にテキストブロック内に指定の文字列を表示することです。
WPF
MVVM構成
XAML
View.csとViewModel.csのみしか使用しない
Viewにはこれ以上の実装はしない。
ViewmoModel内だけで実装したい
発生している問題・エラーメッセージ
エラーは発生していません。 デバックした際に望んだ値は取得できています。 ただ、textblock内に表示だけができていません。
該当のソースコード
ViewModel
1 2using System.Diagnostics; 3using System; 4using System.Windows.Input; 5using System.ComponentModel; 6 7namespace WpfSample2Button 8{ 9 public class MainViewModel : INotifyPropertyChanged 10 { 11 12 public TestText Text { get; set; } 13 public event PropertyChangedEventHandler PropertyChanged; 14 MainViewModel mainViewModel = new MainViewModel(); 15 16 protected virtual void OnPropertyChanged(string name) 17 { 18 PropertyChanged(this, new PropertyChangedEventArgs(name)); 19 } 20 class MyCommand : ICommand 21 { 22 private Action<object> _action; 23 public event EventHandler CanExecuteChanged; 24 25 public MyCommand(Action<object> action) 26 { 27 _action = action; 28 } 29 public bool CanExecute(object parameter) 30 { 31 return true; 32 } 33 public void Execute(object parameter) 34 { 35 _action(parameter); 36 // parameterはnull 37 } 38 public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty); 39 } 40 41 private ICommand _okButton; 42 public ICommand OkButton 43 { 44 get 45 { 46 return _okButton = new MyCommand((o) => 47 { 48 mainViewModel.PutText= new Text( new TestText { PutText = "hoge" }); 49 OnPropertyChanged("getText"); 50 } 51 52 ); 53 54 } 55 } 56 57 public class TestText 58 { 59 public string _putText; 60 public string PutText 61 { 62 63 get { _putText; } 64 set { _putText = Value; } 65 } 66 } 67 68 public MainViewModel() 69 { 70 71 } 72 } 73}
該当のソースコード
XAML
1<Window x:Class="WpfSample2Button.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:WpfSample2Button" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="450" Width="800"> 9 <Grid> 10 <Button Content="OK" Command="{Binding OkButton}" Width = "50" Height = "50" /> 11 </Grid> 12 <Grid> 13 <TextBlock Content="Text" Text="{Binding PutText Mode="OneWay" UpdateSourceTrigger=PropertyChanged}" Width = "50" Height = "50" /> 14 </Grid> 15</Window>
試したこと
値を渡す先のプロパティの変更通知(OnPropertyChanged)を実装しました。
ここも通るのですがOnPropertyChangedメソッド内のPropertyChangedがnullなのが気になってます。
今回のコードには不要だと思い記載はしておりませんが、そのほかにDateGrid内を選択すると選択対象の値を他のDateGrid内に表示するということをしています。
その内にもこのOnPropertyChangedでプロパティの変更通知をし完了しており
OnPropertyChangedメソッド内のPropertyChangedはnullではありませんでした。
補足情報(FW/ツールのバージョンなど)
TextBlockのTextプロパティ(getText)にバインドしています