WPF通知更改(INotifyPropertyChanged)
通知更改时可创建一个类,继承接口来实现
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallermemberName] string PropertyName = "" )
//使用这个CallermemberName这个特性使得默认值为空
{
PropertyChanged?.Ivnoke(this,new PropertyChangedEventArgs(PropertyName));
}
}
public class MainViewMdel : INotifyPropertyChanged
{
public MainViewModel()
{
Name = "Hello";
Show Command = new MyCommand(Show);
}
Private string title
public string Title
{
ger {return Title}
set
{
title = value;
OnPropertyChanged();
}
}
Private string name
public string Name
{
ger {return Name}
set
{
title = value;
OnPropertyChanged();
}
}
public Mycommand ShowCommand {get ;set;}
public void Show()
{
Name = "点击按钮!";
MessageBox.Show(Name);
}
xaml界面
<Grid>
<StackPanel>
<TextBox Text = "{Binding Name}"/>
<TextBox Text = "{Binding Title}"/>
<Botton Command = "{Binding ShowCommand}" Content = "Show"/>
</StackPanel>
点击按钮,触发事件,更新内容
WPF框架(MvvmLIght)
使用社区中的已经做好的包
来减少我们的工作量
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeCoponent();
this.DataContext = new MainViewModel();
//注册一个来接收string类型的参数,地址是Token1
Messenger.Default.Register <string> (this ,"Token1",Show);
}
void Show (string value)
{
messageBox.Show(value);
}
private void Button_Click(object sender,RoutedEventArgs e)
{
MessageBox.Show("点击了按钮");
}
}
WPF框架(Microsoft.ToolkitMvvM)
public partial class MainWindow : Window
{
InitializeCoponent();
this.DataContext = new MainViewModel();
//注册一个来接收string类型的参数,地址是Token1
WeakReferebceMessenger.Default.Register <string,string > (this ,"Token1",(s,e)=>{});
}
void Show (string value)
{
messageBox.Show(value);
}
void Show(string value)
{
MEssageBox.Show(value);
}
private void Button_Click(object sender,RoutedEventArgs e)
{
MessageBox.Show("点击了按钮");
}
}