Data binding to a UserControl in WPF

后端 未结 4 2025
庸人自扰
庸人自扰 2021-02-05 20:10

I have a UserControl that I want to participate in data binding. I\'ve set up the dependency properties in the user control, but can\'t get it work.

The uc displays the

4条回答
  •  迷失自我
    2021-02-05 21:02

    You set the DataContext in the Control to itself, thus overwriting the DataContext when using this Control in other controls. Taking your binding as example in your situation:

     
    

    Once loaded and all the Datacontext is set, it will look for the path MyString in your BlueTextBox thing control due to you setting the DataContext to it. I guess this is not how you intended this to work ;).

    Solution:

    Change the text binding either one of the 2 bindings:

    {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:BlueTextBox}}, Path=BlueText}
    

    or

    Name your control Root (or something like that)

    And remove the

    DataContext = this;
    

    from the constructor of your UserControl and it should work like a charm..

提交回复
热议问题