2017-10-11 36 views
0

我遇到問題,我有一個現有的模型對象,我無法擴展。實際問題有點複雜,所以我嘗試將其分解。使用DependencyProperty在TextBox上添加IsDirty-Flag

我想用依賴項屬性擴展TextBox以指示文本已更改。所以,我想出了以下解決方案:

public class MyTextField : TextBox 
{ 
    public MyTextField() 
    { 
     this.TextChanged += new TextChangedEventHandler(MyTextField_TextChanged); 
    } 

    private void MyTextField_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     IsDirty = true; 
    } 
    public static DependencyProperty IsDirtyProperty = DependencyProperty.Register(
     "IsDirtyProperty", 
     typeof(bool), 
     typeof(MyTextField), 
     new PropertyMetadata(false)); 

    public bool IsDirty 
    { 
     get { return (bool)GetValue(IsDirtyProperty); } 
     set { SetValue(IsDirtyProperty, value); } 
    } 
} 

XAML:

<my:MiaTextField Text="{Binding Barcode}" IsDirty="{Binding IsDirty}"/> 

所以,如果我更改TextBox文本中,isDirty物業應更改爲true。 但我得到了System.Windows.Markup.XamlParseException:綁定只能設置爲「DependencyObject」的「DependencyProperty」。

回答

1

或者你可以在TextProperty的override the PropertyMetadata

public class MyTextBox : TextBox 
{ 
    static MyTextBox() 
    { 
     TextProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata("", IsDirtyUpdateCallback)); 
    } 

    private static void IsDirtyUpdateCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     if (d is MyTextBox tb && e.NewValue != e.OldValue && e.Property == TextProperty) 
     { 
      tb.IsDirty = (string)e.OldValue != (string)e.NewValue; 
     } 
    } 



    public bool IsDirty 
    { 
     get { return (bool)GetValue(IsDirtyProperty); } 
     set { SetValue(IsDirtyProperty, value); } 
    } 

    public static readonly DependencyProperty IsDirtyProperty = 
     DependencyProperty.Register("IsDirty", typeof(bool), typeof(MyTextBox), new PropertyMetadata(true)); 
} 

自動設置您的IsDirty:o)更多然後一路羅馬。但是,對於你的proplem這是有點用大炮射擊小鳥(德國諺語)

+0

。不幸的是綁定不起作用。在GridView中,我有我的 'Textbox'綁定了一個'ObservableCollection'。 'IsDirtyProperty' -DP設置正確。 – Marcel

+0

@Marcel:你試過我的建議嗎? – mm8

+0

@ mm8是的但綁定不起作用 – Marcel

5

通行證 「IsDirty」,即CLR包裝的依賴項屬性的名稱,爲DependencyProperty.Register方法:

public static DependencyProperty IsDirtyProperty = DependencyProperty.Register(
    "IsDirty", 
    typeof(bool), 
    typeof(MyTextField), 
    new PropertyMetadata(false)); 

如果您正在使用C#6 /的Visual Studio 2015年或以後,你可以使用在nameof操作:

public static DependencyProperty IsDirtyProperty = DependencyProperty.Register(
    nameof(IsDirty), 
    typeof(bool), 
    typeof(MyTextField), 
    new PropertyMetadata(false)); 
+1

你可以添加編譯時的安全性,並通過使用'nameof(IsDirty)'' –

+0

去除魔術字符串如果你使用最近的VisualStudio,你幾乎可以得到所有這些通過'propdp + TAB + TAB' - 依賴屬性的代碼片段可用於insiode源代碼。該類必須從DependencyObject派生,但TextBox確實如此。首先非常感謝 –