【发布时间】:2013-05-29 12:58:45
【问题描述】:
我无法从另一个DataTemplate 绑定到DataTemplate,这是因为运行时数据源不存在吗?
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>
<DataTemplate x:Key="Employees">
<StackPanel>
<ListView ItemsSource="{Binding Path=Employees}">
<ListView.View>
<GridView>
<GridViewColumn Header="FirstName">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DockPanel>
<TextBlock Text="{Binding FirstName}"/>
</DockPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="LastName">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DockPanel>
<TextBlock Text="{Binding LastName}"/>
</DockPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="Company">
<StackPanel>
<TextBlock>Company data</TextBlock>
<ListView
<!-- Bind current data source -->
ItemsSource="{Binding}"
<!-- Static resource (nested template) -->
ItemTemplate="{StaticResource Employees}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<StackPanel>
<TextBlock>Companies:</TextBlock>
<ListView ItemsSource="{Binding Companies}" ItemTemplate="{StaticResource Company}" />
</StackPanel>
</Page>
我正在尝试使员工 DataTemplate 可重复使用,因为在其他数据 DataTemplates 中引用它会很有用。公司绑定DataTemplate:<ListView ItemsSource="{Binding}" ItemTeplate="{StaticResource Employees}" />是不是有问题
为什么员工不绑定?
【问题讨论】:
-
您在 VS 的调试输出窗口中是否收到任何
BindingExpression错误? -
没有错误。使用 snoop 时,未设置列表框的 Value 属性
-
您需要为您的虚拟机/代码隐藏添加您的类定义,其中
Company1 和Company2使用它们的类型类定义。不知道为什么你在Company1中绑定到{Binding Path=Employees}而Company2只是{Binding},如果这就是你的类的结构。 -
VM 已按应有的方式定义。我遇到的问题是从 DataTemplate (Company2) 中绑定到员工,当它全部在线 (Company1) 时它工作正常,但这会给我在现实生活中造成巨大的重复。在 company1 中,ListView 绑定到Employees,这是DataTemplates ItemsSource 的一个属性(Company1 obj,其中Employees 是一个列表属性)。在 DataTemplate Company2 中,我尝试引用 DataTemplate Employees,但我将其绑定到当前源({Binding})
-
我已经删除了有效的代码,只留下了错误的样本以使事情更清楚。
标签: wpf xaml binding datatemplate