您的第一個錯誤是正確的。 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