WPF 使用附加属性和行为执行 ICommand

WPF execute ICommand using attached properties and behaviours

所以我正在学习附加属性和附加行为。我有一个 TextBox,每次更改文本时,我想在我的 ViewModel 中执行一些 ICommand SomeCommand,我会像这样在视图中绑定:

<TextBox ... TextUpdateCommand="{Binding Path=SomeCommand}" MonitorTextBoxProperty=true />

MonitorTextBoxProperty 只是一个 属性,它监听 TextChanged 事件,然后在触发 TextChanged 时执行 ICommand SomeCommand。执行的ICommand SomeCommand应该来自TextUpdateCommandProperty。我如何 link 这个 ICommand SomeCommandOnTextBoxTextChanged 执行它?

代码:

//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));

只需使用附加的 属性 的获取访问器获取 TextBoxTextUpdateCommand 属性 的当前值。试试这个:

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)调用DependencyProperty.RegisterAttached.