【发布时间】:2018-08-16 13:47:16
【问题描述】:
所以我正在学习附加属性和附加行为。我有一个TextBox,每次更改文本时,我想在我的 ViewModel 中执行一些ICommand SomeCommand,我会像这样在视图中绑定:
<TextBox ... TextUpdateCommand="{Binding Path=SomeCommand}" MonitorTextBoxProperty=true />
MonitorTextBoxProperty 只是一个监听TextChanged 事件然后在TextChanged 被触发时执行ICommand SomeCommand 的属性。执行的ICommand SomeCommand 应该来自TextUpdateCommandProperty。如何链接此ICommand SomeCommand 以从OnTextBoxTextChanged 执行它?
代码:
//Property and behaviour for TextChanged event
public static int GetMonitorTextBoxProperty(DependencyObject obj)
{
return (int)obj.GetValue(MonitorTextBoxProperty);
}
public static void SetMonitorTextBoxProperty(DependencyObject obj, int value)
{
obj.SetValue(MonitorTextBoxProperty, value);
}
public static readonly DependencyProperty MonitorTextBoxProperty =
DependencyProperty.RegisterAttached("MonitorTextBox", typeof(bool), typeof(this), new PropertyMetadata(false, OnMonitorTextBoxChanged));
private static void OnMonitorTextBoxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = (d as TextBox);
if (textBox == null) return;
textBox.TextChanged -= OnTextBoxTextChanged;
if ((bool)e.NewValue)
{
textBox.TextChanged += OnTextBoxTextChanged;
}
}
private static void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
// Execute ICommand by command.Execute()
}
// Property for attaching ICommand that is executed on TextChanged
public static int GetTextUpdateCommandProperty(DependencyObject obj)
{
return (int)obj.GetValue(TextUpdateCommandProperty);
}
public static void SetTextUpdateCommandProperty(DependencyObject obj, int value)
{
obj.SetValue(TextUpdateCommandProperty, value);
}
public static readonly DependencyProperty TextUpdateCommandProperty =
DependencyProperty.RegisterAttached("TextUpdateCommand", typeof(ICommand), typeof(this), new PropertyMetadata(null));
【问题讨论】:
标签: c# .net wpf mvvm attached-properties