Reputation: 9975
In Silverlight XAML, I think I've just realized that a DataContext declaration on a nested container is relative to the parent container's DataContext. Can you all please confirm.
If so, then let me ask this: On a child XAML container element (i.e. StackPanel) how would you would jump out of that relative DataContext tree, and start at a higher place, or a start a different DataContext all together if you wanted set the DataContext on the StackPanel to a different root context?
In other words, how to break the child DataContext free of the parent DataContext?
(Looking for XAML code solution/syntax)
Upvotes: 2
Views: 5646
Reputation: 4970
Your first assumnption is correct. The DataContext is kind of inherited by the nested elements.
On a child XAML container element you can always redefine what the DataContext is.
See example below:
<UserControl.Resources>
<local:Customer x:Key="Cust">
<local:Supplier x:Key="Supp">
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource Cust}">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0">
<TextBlock Text="Customer Name: " />
<TextBox Text="{Binding Path=Name}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Row="1" DataContext="{StaticResource Supp}">
<TextBlock Text="Supplier Name: " />
<TextBox Text="{Binding Path=Name}"/>
<TextBlock Text=" Telephone: " />
<TextBox Text="{Binding Path=Telephone}"/>
</StackPanel>
</Grid>
And here are the "Model" classes for the example above:
public class Customer
{
public Customer()
{
Name = "Customer name";
Address = "Customer address";
}
public string Name { get; set; }
public string Address { get; set; }
}
public class Supplier
{
public Supplier()
{
Name = "Supplier name";
Address = "Supplier address";
Telephone = "(555)555-5555";
}
public string Name { get; set; }
public string Address { get; set; }
public string Telephone { get; set; }
}
Upvotes: 3