从DependencyProperty更新辅助属性

时间:2017-07-10 11:04:40

标签: c# wpf

我有一个基于TextBox控件的WPF控件:

public class DecimalTextBox : TextBox

我有一个绑定的依赖项属性,它管理数值,并负责设置Text属性:

public decimal NumericValue
{
    get { return (decimal)GetValue(NumericValueProperty); }
    set
    {
        if (NumericValue != value)
        {
            SetValue(NumericValueProperty, value);
            SetValue(TextProperty, NumericValue.ToString());                    

            System.Diagnostics.Debug.WriteLine($"NumericValue Set to: {value}, formatted: {Text}");
        }
    }
}

protected override void OnTextChanged(TextChangedEventArgs e)
{            
    base.OnTextChanged(e);

    if (decimal.TryParse(Text, out decimal num))
    {
        SetValue(NumericValueProperty, num);
    }
}

在向文本框本身输入值时(这会更新基础值等),这很有效。但是,当更改NumericValue的bound属性时,尽管更新了NumericValue DP,但Text属性不会更新。在我已经完成的测试中,似乎原因是更新绑定值时不调用上面的set方法。有问题的绑定看起来像这样:

<myControls:DecimalTextBox NumericValue="{Binding Path=MyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

有人能指出我为什么这个属性设定者没有开火的正确方向,还是有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:1)

正如Custom Dependency PropertiesXAML Loading and Dependency Properties中所述,您不应在依赖项属性的CLR包装器中调用除SetValuePropertyChangedCallback之外的任何内容:

  

由于属性设置的XAML处理器行为的当前WPF实现完全绕过包装器,因此不应将任何其他逻辑放入自定义依赖项属性的包装器的集定义中。如果将这样的逻辑放在set定义中,那么当在XAML中而不是在代码中设置属性时,将不会执行逻辑。

为了获得有关值更改的通知,您必须使用依赖项属性元数据注册public static readonly DependencyProperty NumericValueProperty = DependencyProperty.Register( "NumericValue", typeof(decimal), typeof(DecimalTextBox), new PropertyMetadata(NumericValuePropertyChanged)); public decimal NumericValue { get { return (decimal)GetValue(NumericValueProperty); } set { SetValue(NumericValueProperty, value); } } private static void NumericValuePropertyChanged( DependencyObject obj, DependencyPropertyChangedEventArgs e) { var textBox = (DecimalTextBox)obj; textBox.Text = e.NewValue.ToString(); }

update_counter

答案 1 :(得分:0)

WPF绑定实际上并没有使用你的getter和setter,而是直接与依赖属性NumericValueProperty交互。要更新文本,请订阅PropertyChanged的{​​{1}}事件,而不是尝试在设置器中执行任何特殊操作。

订阅DependencyProperty定义中的更改,类似于以下内容:

NumericValueProperty
相关问题