繁体   English   中英

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

[英]WPF execute ICommand using attached properties and behaviours

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

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

MonitorTextBoxProperty只是一个属性,它侦听TextChanged事件,然后在ICommand SomeCommand 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));

只需使用附加属性的 get 访问器获取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)应该是调用DependencyProperty.RegisterAttachedtypeof(TheClassName)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM