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

时间:2018-08-16 13:47:16

标签: c# .net wpf mvvm attached-properties

因此,我正在学习附加属性和附加行为。我有一个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));

1 个答案:

答案 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)