[英]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 訪問器獲取TextBox
的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)
應該是調用DependencyProperty.RegisterAttached
的typeof(TheClassName)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.