简体   繁体   中英

Silverlight - relative DataContext in XAML?

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 (ie 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)

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; }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM