因此,我正在学习附加属性和附加行为。我有一个TextBox
,每次更改文本时,我都想在ViewModel中执行一些ICommand SomeCommand
,然后将其绑定在这样的视图中:
<TextBox ... TextUpdateCommand="{Binding Path=SomeCommand}" MonitorTextBoxProperty=true />
MonitorTextBoxProperty
只是一个属性,它侦听TextChanged
事件,然后在触发ICommand SomeCommand
时执行TextChanged
。执行的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));
答案 0 :(得分:1)
只需使用附加属性的get访问器获取TextBox
的{{1}}属性的当前值。试试这个:
TextUpdateCommand
您还应该更改访问器的类型:
private static void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
var command = GetTextUpdateCommandProperty(textBox);
if (command != null)
command.Execute(null);
}
并且public static ICommand GetTextUpdateCommandProperty(DependencyObject obj)
{
return (ICommand)obj.GetValue(TextUpdateCommandProperty);
}
public static void SetTextUpdateCommandProperty(DependencyObject obj, ICommand value)
{
obj.SetValue(TextUpdateCommandProperty, value);
}
应该在typeof(this)
的调用中typeof(TheClassName)
。