1. 使用数据绑定和属性通知
实现步骤
1.1 创建数据模型
csharp
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class MonitorModel : INotifyPropertyChanged
{
private string _monitorValue;
public string MonitorValue
{
get { return _monitorValue; }
set
{
if (_monitorValue != value)
{
_monitorValue = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
1.2 在XAML中绑定属性
xml
<Window x:Class="WpfMonitorVariable.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox Text="{Binding MonitorValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>
1.3 设置数据上下文
csharp
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MonitorModel();
}
}
2. 使用依赖属性
2.1 定义依赖属性
csharp
public static readonly DependencyProperty MonitorValueProperty =
DependencyProperty.Register("MonitorValue", typeof(string), typeof(MonitorModel),
new PropertyMetadata(string.Empty, OnMonitorValueChanged));
private static void OnMonitorValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var monitorModel = d as MonitorModel;
monitorModel?PropertyChanged?.Invoke(monitorModel, new PropertyChangedEventArgs(e.Property.Name));
}
public string MonitorValue
{
get { return (string)GetValue(MonitorValueProperty); }
set { SetValue(MonitorValueProperty, value); }
}
3. 使用消息传递
3.1 创建消息服务
csharp
public class MessageService : IMessageService
{
public event Action<string> MonitorValueChanged;
public void RaiseMonitorValueChanged(string value)
{
MonitorValueChanged?.Invoke(value);
}
}
3.2 订阅和发布消息
csharp
public partial class MainWindow : Window
{
private readonly IMessageService _messageService;
public MainWindow(IMessageService messageService)
{
InitializeComponent();
_messageService = messageService;
_messageService.MonitorValueChanged += MessageService_MonitorValueChanged;
}
private void MessageService_MonitorValueChanged(string value)
{
// 更新UI或执行其他逻辑
}
}
4. 使用事件
4.1 定义事件
csharp
public class MonitorModel
{
private string _monitorValue;
public string MonitorValue
{
get { return _monitorValue; }
set
{
if (_monitorValue != value)
{
_monitorValue = value;
OnValueChanged();
}
}
}
public event Action<string> ValueChanged;
protected void OnValueChanged()
{
ValueChanged?.Invoke(_monitorValue);
}
}
4.2 订阅事件
csharp
var model = new MonitorModel();
model.ValueChanged += Model_ValueChanged;
private void Model_ValueChanged(string value)
{
// 处理变量值改变
}
结论
往期精品推荐: