CommunityToolkit.Mvvm
public class ViewModel : ObservableObject { public ViewModel() { ShowCommand = new RelayCommand<string>(Show); } private string name; public string Name { get { return name; } set { name = value; OnPropertyChanged(); } } public RelayCommand<string> ShowCommand { get; } public void Show(string content) { Name = "点击了按钮!"; MessageBox.Show(content); //发送消息 给Token1的地址发送一个string类型的值 content WeakReferenceMessenger.Default.Send(content, "Token1"); } }
<Grid> <StackPanel> <TextBox Text="{Binding Name}"/> <TextBox x:Name="txt" Width="200" Height="25"/> <Button Command="{Binding ShowCommand}" CommandParameter="{Binding ElementName=txt,Path=Text}" Width="50" Height="25">button</Button> </StackPanel> </Grid>
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new ViewModel() { Name = "Hello!" }; //注册一个接收string类型参数的消息,地址是:Token1 WeakReferenceMessenger.Default.Register<string,string>(this, "Token1", Show); } public void Show(object recipient, string value) { MessageBox.Show($"来自Token1的消息:{value}"); } }