Data binding to a UserControl in WPF

后端 未结 4 2031
庸人自扰
庸人自扰 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 20:56

    I know this is an old topic but still.

    Also mention the PropertyChangedCallback on the UIPropertyMetadata during registering your DP

    0 讨论(0)
  • 2021-02-05 20:58

    Possibly you need to add to your property FrameworkPropertyMetadata where specify FrameworkPropertyMetadataOptions.AffectsRender and AffectsMeasure.

    FrameworkPropertyMetadataOptions enumeration MSDN article

    0 讨论(0)
  • 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:

    <src:BlueTextBox BlueText="{Binding Path=MyString}" /> 
    

    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)

    <UserControl x:Name="Root"
    
    {Binding ElementName=Root, Path=BlueText}
    

    And remove the

    DataContext = this;
    

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

    0 讨论(0)
  • 2021-02-05 21:05

    I think in this case you need to set the ElementName property in the binding. Something like this:

    <UserControl x:Class="Binding2.BlueTextBox" x:Name="blueTextBox"...
    <Grid>
        <TextBox x:Name="myTextBox" Text="{Binding ElementName=blueTextBox, Path=BlueText}" Foreground="Blue" Width="100" Height="26" />
    </Grid>
    
    0 讨论(0)
提交回复
热议问题