依赖属性 - 更新源

Jas*_*ter 8 data-binding wpf

我对自定义依赖属性疯狂.我已在这里检查了大量的线程,但还没有找到任何解决方案.我想要做的是,如果源提供特定值(对于给定示例为null),则替换Property的值.无论我尝试什么,源中的属性值都保持为null并且永远不会更新.

这是我的自定义控件:

public class TextBoxEx : TextBox
{
    public TextBoxEx()
    {
        TrueValue = 0;
        this.TextChanged += (s, e) =>
        {
            TrueValue = Text.Length;
            SetCurrentValue(MyPropertyProperty, TrueValue);
            var x = BindingOperations.GetBindingExpression(this, MyPropertyProperty);
            if (x != null)
            {
                x.UpdateSource();
            }
        };
    }

    public int? TrueValue { get; set; }

    public int? MyProperty
    {
        get { return (int?)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(int?), typeof(TextBoxEx), new PropertyMetadata(null, PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue == null)
        {
            d.SetCurrentValue(MyPropertyProperty, (d as TextBoxEx).TrueValue);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我绑定的DataContext:

public class VM : INotifyPropertyChanged
{
    private int? _Bar = null;

    public int? Bar
    {
        get { return _Bar; }
        set
        {
            _Bar = value;
            OnPropertyChanged("Bar");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的绑定看起来像这样:

<local:TextBoxEx MyProperty="{Binding Bar, UpdateSourceTrigger=PropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)

请记住:我需要一个TwoWay绑定,因此OneWayToSource对我不起作用.

知道我没有进入这里吗?

H.B*_*.B. 8

您只需将绑定设置为双向即可.但由于这应该是默认值,您可以使用以下元数据相应地注册属性:

... new FrameworkPropertyMetadata(null,
                                  FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                                  PropertyChangedCallback)
Run Code Online (Sandbox Code Playgroud)

TextChanged不需要在处理程序中获取表达式并手动更新源代码,因此我将删除该代码.


如果未在绑定上显式设置模式,则将使用以下文档中的默认值:

默认值:使用绑定目标的默认模式值.每个依赖项属性的默认值都不同.通常,用户可编辑的控件属性(例如文本框和复选框的属性)默认为双向绑定,而大多数其他属性默认为单向绑定.以编程的方式来确定一个依赖属性是否结合单向或默认双向是让使用属性的属性元数据的getMetaData然后检查的布尔值BindsTwoWayByDefault财产.