C# INotifyPropertyChangedを使ってBindingした値の変更をControlに反映させる
public class Class1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] String propertyName = "")
{
// propertyName 呼び出し元のプロパティ名
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private DateTime dateTime1 = DateTime.Now;
public DateTime DateTime1
{
get { return dateTime1; }
set
{
if (dateTime1 != value)
{
dateTime1 = value;
RaisePropertyChanged();
}
}
}
// 比較用
public DateTime DateTime2 { get; set; } = DateTime.Now;
}
<Grid>
<StackPanel>
<TextBlock Text="{Binding DateTime1}"/>
<TextBlock Text="{Binding DateTime2}"/>
<Button Content="button" Click="Button_Click"/>
</StackPanel>
</Grid>
public partial class MainWindow : Window
{
Class1 class1=new Class1();
public MainWindow()
{
InitializeComponent();
this.DataContext = class1;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
class1.DateTime1 = DateTime.Now;
class1.DateTime2 = DateTime.Now;
}
}