简体   繁体   中英

Custom Dependency Property bindings

I am trying to implement a numberBox class inherited from TextBox

 public class numberBox : TextBox

And I declared a custom 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); }
    }

In constructor of numberBox, I have a binding to synchronize Text and number

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

In one case when I use the numberBox like this way

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

"dg" is a DataGrid, my goal is that when DataGrid selection changed, the numberBox display the value of selected item

PS I know I can use DataGrid.SelectionChanged event to achieve the same behavior but I just want to learn more about binding

Everything is working fine so far, when I select different row of DataGrid, the numberBox displays correct value, however, when the numberBox got focus, be edited, after losing focus, the numberProperty binding was gone, which means when DataGrid selected item changed, it doesn't bring the value into numberBox anymore

I set a break point and check "this.GetBindingExpression(numberProperty)" in numberBox, and it returns null after this numberBox be edited and lost focus

Does anyone knows the reason and how should I do to fix this?

Many thanks.

You can fix it by setting

b.Mode = BindingMode.OneWay;

in the constructor of numberBox. By the binding back of TextProperty to source "number" the binding between numberProperty and the grid is cleared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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