實際上,我發現布爾附加屬性解決方案有點骯髒和笨拙的方式,你必須找到一個扭曲,以確保下一組視圖模型屬性將真正引發附加屬性更改事件。
一個簡單和更優雅的解決方案是綁定你的行爲屬性類型,你可以確保下一個值將永遠不同於前一個,從而確保你的附屬屬性改變事件會每次提升。
想到的最簡單的類型是int。然後將溶液的通常的組合:
行爲:
class TextBoxFocusBehavior
{
public static int GetKeepFocus(DependencyObject obj)
{
return (int)obj.GetValue(KeepFocusProperty);
}
public static void SetKeepFocus(DependencyObject obj, int value)
{
obj.SetValue(KeepFocusProperty, value);
}
// Using a DependencyProperty as the backing store for KeepFocus. This enables animation, styling, binding, etc...
public static readonly DependencyProperty KeepFocusProperty =
DependencyProperty.RegisterAttached("KeepFocus", typeof(int), typeof(TextBoxFocusBehavior), new UIPropertyMetadata(0, OnKeepFocusChanged));
private static void OnKeepFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox t = d as TextBox;
if (t != null)
{
t.Focus();
}
}
}
視圖模型屬性:
public int InputFocus
{
get { return _inputFocus; }
private set
{
_inputFocus = value;
Notify(Npcea.InputFocus);
}
}
使用該附加的行爲的:
<TextBox v:TextBoxFocusBehavior.KeepFocus="{Binding InputFocus}"/>
而最終使用VM中的財產:
和
public void YouMethod()
{
//some code logic
InputFocus++;//<= the textbox focus
}
一些非常壞的思想精神可以說,這種邏輯被綁定到INT32大小限制。那麼......我現在就選擇忽略它們;-)
我不認爲有一個元素的名稱本身就是不好的設計,但給元素一個名稱,以便您可以在代碼隱藏中引用它,應該避免。我沒有看到上面的觀點有什麼不妥。 – lesscode 2010-05-14 14:50:06
考慮是否要使用觸發器在視圖中執行任何特殊操作(動畫和其他狀態更改) - 名稱對於這些操作非常重要。 – Gusdor 2011-07-26 12:36:28