Binding to custom dependency property - again

前端 未结 1 582
一生所求
一生所求 2020-12-14 17:14

The task: implement the simplest Dependency Property ever, which can be used in xaml like that:



        
相关标签:
1条回答
  • 2020-12-14 17:25

    The Text property is located on the DataContext of the MainWindow not of the UserControl.

    So change this line <uc:MyUserControl1 MyTextProperty="{Binding Text}"/> into this:

    <uc:MyUserControl1 MyTextProperty="{Binding Text, ElementName=MyMainWindow}"/>
    

    Which will tell the Binding that you're talking about the Text element located in you MainWindow. Of course, since in this example I used ElementName, you're going to want to name your window MyMainWindow...

    So add this to your MainWindow:

    <Window  Name="MyMainWindow" ..... />
    

    If you rather not name your window, you can use the RelativeSource FindAncestor binding like this:

    <wpfApplication6:MyUserControl1 MyTextProperty="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"/>
    

    In both ways, you are asking to find the property named 'Text' in the DataContext of the window.

    0 讨论(0)
提交回复
热议问题