Binding causes StackOverflow

前端 未结 2 423
死守一世寂寞
死守一世寂寞 2020-12-12 03:40

Im not sure what I am doing wrong here.

Lets say, I have two UserControls BoxAand BoxB. Both have a DependencyProperty called Text

2条回答
  •  北海茫月
    2020-12-12 03:55

    If you are building a UserControl with bindable properties (i.e. dependency properties), you must under no circumstances explicitly set the UserControl's DataContext, be it to the control instance or to any private view model.

    If you do that, a Binding like

    
    

    will no longer work. That Binding expects a Title property in the object in the current DataContext. The DataContext property value is usually inherited from the parent element of the UserControl, e.g. the Window. However, since you've explicitly set the DataContext, this mechanism is avoided.

    This becomes particularly confusing with equally named properties in UserControls. When you write

    
    

    in UserControl BoxB, your expectation is that the Binding source property is BoxB.Text. In fact it is BoxA.Text, because BoxA's DataContext is the BoxA instance.


    So remove any

    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    

    lines and write the Bindings in the UserControl's XAML with RelativeSource like this:

    
    
    
    

提交回复
热议问题