簡體   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