问题
How are DataContext
in UserControls usually set? If I do something like the below in my UserControl,
DataContext = this
In my Window or other Controls when I want to use the Control with a Binding, I will have to have a RelativeSource
to point to the Window/UserControl
<local:UserControl1 TextContent="{Binding Text1, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
Is the way to bind Controls within UserControls: set use RelativeSource
in UserControls instead of DataContext
?
<UserControl x:Class="SetCurrentValueTest.UserControl1" ...>
<TextBox Text="{Binding Path=TextContent, RelativeSource={RelativeSource AncestorType={x:Type local:UserControl1}}}" />
</UserControl>
回答1:
I dunno if it is what you are looking for, but if you want to bind to the UserControls Dependency-Properties, use this:
<UserControl x:Class="SetCurrentValueTest.UserControl1" ...>
<TextBox Text="{Binding Path=TextContent, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
</UserControl>
And if you want to bind to the UserControl's DataContext, use this Binding:
<UserControl x:Class="SetCurrentValueTest.UserControl1" ...>
<TextBox Text="{Binding Path=DataContext.TextContent, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
</UserControl>
Not that I am specifying UserControl as Ancestor-Type and not your Concrete Type (UserControl1).
来源:https://stackoverflow.com/questions/4237443/datacontext-in-usercontrols