2

在 Silverlight XAML 中,我想我刚刚意识到嵌套容器上的 DataContext 声明与父容器的 DataContext 相关。请大家确认一下。

如果是这样,那么让我问这个问题:在一个子 XAML 容器元素(即 StackPanel)上,你将如何跳出那个相关的 DataContext 树,并从更高的位置开始,或者如果你想设置一个不同的 DataContext 一起开始StackPanel 上的 DataContext 到不同的根上下文?

换句话说,如何从父 DataContext 中打破子 DataContext?

(寻找 XAML 代码解决方案/语法)

4

2 回答 2

3

你的第一个假设是正确的。DataContext 是由嵌套元素继承的。

在子 XAML 容器元素上,您始终可以重新定义 DataContext 是什么。

请参见下面的示例:


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

以下是上述示例的“模型”类:


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

于 2009-03-04T18:26:05.710 回答
1

查看这个博客,它详细介绍了一个代理类,用于从 xaml 中完成您需要的所有工作。

[ http://weblogs.asp.net/dwahlin/archive/2009/08/20/creating-a-silverlight-datacontext-proxy-to-simplify-data-binding-in-nested-controls.aspx][1]

于 2010-07-28T01:29:49.370 回答