UserControl's DataContext

前端 未结 5 1696
[愿得一人]
[愿得一人] 2020-11-29 23:47

I\'m creating a UserControl I want to use something like this:


相关标签:
5条回答
  • 2020-11-30 00:12

    Why can't you use <UserControl DataContext="{RelativeSource Self}">?

    This is how you would use the control

    <Grid DataContext="{StaticResource ViewModel}">
        <!-- Here we'd expect this control to be bound to -->
        <!-- ColorToUse on our ViewModel resource          -->
        <controls:ColorWithText Color="{Binding ColorToUse}" />
    </Grid>
    

    Now because we've hardcoded our data-context in the control it will instead attempt to lookup ColorToUse property on the ColorWithText object not your ViewModel, which will obviously fail.

    This is why you can't set the DataContext on the user control. Thanks to Brandur for making me understand that.

    What is the best way to do something like this?

    Instead you should set the DataContext in the first child UI element in your control.

    In your case you want

    <StackPanel 
      DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
      Orientation="Horizontal" >
    

    Now you have a DataContext which refers to your control so you can access any properties of that control using relative bindings.

    0 讨论(0)
  • 2020-11-30 00:14

    You should be using

    {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=Color}
    

    for Databinding Related doubts always refer this sheet.
    http://www.nbdtech.com/Blog/archive/2009/02/02/wpf-xaml-data-binding-cheat-sheet.aspx

    0 讨论(0)
  • 2020-11-30 00:15

    For first one, try :

    <UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
    

    And for second question, I think using ElementName or AncestorBinding is best way to bind to UserControl's properties.

    0 讨论(0)
  • 2020-11-30 00:19

    You can set the datacontext to self at the constructor itself.

    public ColorWithText()
    {
     InitializeComponent();
     DataContext = this;
    }
    

    Now you can simply say

    <UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
        <StackPanel Orientation="Horizontal" >
            <Border Width="15" Height="15" Background="{Binding Color}" />
            <TextBlock Text="{Binding Text}" />
        </StackPanel>
    </UserControl>
    
    0 讨论(0)
  • 2020-11-30 00:33

    I know this has been answered but none of the explanations give an Understanding of DataContext and how it works. This link does a great job for that.

    EVERYTHING YOU WANTED TO KNOW ABOUT DATABINDING IN WPF, SILVERLIGHT AND WP7 (PART TWO)

    In answer to your question #1

    Why doesn't <UserControl DataContext="{RelativeSource Self}"> work?

    This is a summary of the above link. DataContext should not be set to Self at UserControl Element level. This is because it breaks the Inheritance of the DataContext. If you do set it to self and you place this control on a Window or another control, it will not inherit the Windows DataContext.

    DataContext is inherited to all lower Elements of the XAML and to all the XAML of UserControls unless it is overwritten somewhere. By setting the UserControl DataContext to itself, this overwrites the DataContext and breaks Inheritance. Instead, nest it one Element deep in the XAML, in your case, the StackPanel. Put the DataContext binding here and bind it to the UserControl. This preserves the Inheritance.

    See also this link below for a detailed explanation of this.

    A SIMPLE PATTERN FOR CREATING RE-USEABLE USERCONTROLS IN WPF / SILVERLIGHT

    In answer to your question #2
    What is the best way to do something like this?

    See code example below.

    <UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
        <StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=ThisControl}">
        <Border Width="15" Height="15" Background="{Binding Color" />
        <TextBlock Text="{Binding Text}" />
    </StackPanel>
    

    Note that once you do this, you will not need the ElementName on each binding.

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