2017-10-11 38 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确实如此。首先非常感谢 –