繁体   English   中英

自定义依赖项属性绑定

[英]Custom Dependency Property bindings

我正在尝试实现从TextBox继承的numberBox类

 public class numberBox : TextBox

我声明了一个自定义的DependencyProperty numberProperty

 public static readonly DependencyProperty numberProperty = DependencyProperty.Register("number", typeof(object), typeof(numberBox), new PropertyMetadata(0));
    public object number
    {
        get { return GetValue(numberProperty); }
        set { SetValue(numberProperty, value); }
    }

在numberBox的构造函数中,我有一个绑定来同步文本和数字

 public numberBox()
    {
        Binding b = new Binding("number");            
        b.Source = this;
        this.SetBinding(TextProperty, b);
    }

在一种情况下,我以这种方式使用numberBox

 <BC:numberBox x:Name="numC1" number={Binding ElementName=dg, Path=SelectedItem.C1} />

“ dg”是一个DataGrid,我的目标是当DataGrid选择更改时,numberBox显示所选项目的值

PS我知道我可以使用DataGrid.SelectionChanged事件来实现相同的行为,但我只想了解有关绑定的更多信息

到目前为止,一切工作正常,当我选择DataGrid的不同行时,numberBox显示正确的值,但是,当numberBox获得焦点时,对其进行编辑,失去焦点后,numberProperty绑定就消失了,这意味着当DataGrid选择的项目更改时,它不再将值带入numberBox

我设置一个断点并在numberBox中检查“ this.GetBindingExpression(numberProperty)”,在编辑此numberBox并失去焦点后,它返回null

有谁知道原因,我应该如何解决?

非常感谢。

您可以通过设置

b.Mode = BindingMode.OneWay;

在numberBox的构造函数中。 通过将TextProperty绑定回源“数字”,可以清除numberProperty和网格之间的绑定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM