1.MVVM模式
前台:
<StackPanel>
<TextBox Margin="10" Height="20" Background="LightCyan" x:Name="text1"/>
<TextBox Margin="10,0" Height="20" Background="LightCyan" Text="{Binding Title}"/>
<Button Content="Button" Margin="10" Command="{Binding AddCommand}" CommandParameter="{Binding ElementName=text1,Path=Text}"/>
</StackPanel>
后台:
class MainWindowViewModel:ViewModelBase
{
private string title;
public string Title
{
get { return title; }
set{
title = value;
this.RaisePropertyChanged();
}
}
//带参数
public RelayCommand<string> AddCommand { get; set; }
public MainWindowViewModel()
{
AddCommand = new RelayCommand <string>(Show);
}
private void Show(string str)
{
Title = str;
}
}
2.Messager消息传递
它是一种轻量级、简单易用的消息传递机制,可以有效地解耦 ViewModel 和 View 的依赖关系,从而提高代码的可维护性和可测试性。
/// <summary>
/// 注册订阅事件 (在 View 或 ViewModel 中注册对特定消息的处理方法)
/// </summary>
/// <typeparam name="TMessage">传参类型</typeparam>
/// <param name="recipient">订阅实例</param>
/// <param name="token">发送与接收定义的key值</param>
/// <param name="action">订阅事件触发的action</param>
/// <param name="keepTargetAlive">持续控制实例存在,防止被回收清除</param>
public void Register<TMessage>(object recipient, object token, Action<TMessage> action, bool keepTargetAlive = false);
/// <summary>
/// 注销订阅事件 (取消在 View 或 ViewModel中对特定消息的处理方法的注册)
/// </summary>
/// <typeparam name="TMessage">传参类型</typeparam>
/// <param name="recipient">订阅实例</param>
/// <param name="token">发送与接收定义的key值</param>
void Unregister<TMessage>(object recipient, object token);
/// <summary>
/// 被订阅方触发事件 (在 ViewModel中发送消息,将消息发送给已经注册了该消息的所有接收器)
/// </summary>
/// <typeparam name="TMessage">传参类型</typeparam>
/// <param name="message">参数数据</param>
/// <param name="token">key</param>
public void Send<TMessage>(TMessage message, object token);
注册消息:
public MainWindow()
{
// InitializeComponent call is required to merge the UI
// that is defined in markup with this class, including
// setting properties and registering event handlers
InitializeComponent();
this.DataContext = new MainWindowViewModel();
Messenger.Default.Register<string>(this,"token1",(info)=> { MessageBox.Show(info); });
}
发送消息:
private void Show(string str)
{
Title=str;
Messenger.Default.Send<string>("hello", "token1");
}
注销消息:
Messenger.Default.Unregister<string>(this, "token1");
标签:订阅,object,string,MVVMLight,void,使用,Show,简单,public From: https://www.cnblogs.com/xixi-in-summer/p/17968208