您的第一个错误是正确的。 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; }
}
您的示例在XAML中创建对象。我的对象在构造函数中实例化。那么,由于XAML不在XAML的UserControl.Respources中,因此每个XAML都要使用它们指向对象。 – MattSlay 2009-03-04 18:48:28