views:

29

answers:

1

I'm trying to confirm a binding behavior I believe I have observed, but I'm not exactly sure of.

My original understanding was that a UserControl was sort of a black box, where if you wanted to share information back and forth with the controls contained within, you had to (1) use the DataContext or (2) define them on the surface of the UserControl and bind to these properties.

My original view of the WPF UserControl world:

In the control:

<UserControl x:Name="root" x:Class="MyUserControl">
  <TextBox Text="{Binding Lol, elementName=root}"/>

In the codebehind:

public class MyUserControl : UserControl
{
  public string Lol {get;set;}

In use:

<TextBox ToolTip="Enter your Lol" x:Name="lolSource"/>
<this:MyUserControl Lol="{Binding Text, elementName=lolSource}" />

However, I have seen an instance where it appeared the UserControl's controls were merged seamlessly with its container, so this redirection of bindings through properties defined on the UserControl was not needed.

A custom Window:

public class MyWindow : Window
{
  public string Lol {get;set;}

The window XAML:

<this:MyWindow xmlns:this="clrblah">
  <this:MyUserControl />

the UserControl:

<UserControl>
  <TextBox Text="{Binding Lol}" />

Is this the normal behavior of UserControls? That their content is, seeminlgy, stripped out and placed directly in the visual tree? That the UserControl is not a black box, but is in fact not a box at all?

A: 

I think what is occurring is that your usercontrol is inheriting the datacontext of its parent (the window) since one was not explicitly defined for your usercontrol.

mdm20
The DataContext is inherited. Yes. But, in the example I provided, it is NOT the DataContext that is being inherited. It is a property defined on the custom Window.
Will
But is the datacontext of the window, the window itself?
mdm20