【发布时间】:2011-06-08 01:20:30
【问题描述】:
我有一个 WPF 组合框,里面装满了客户对象。我有一个数据模板:
<DataTemplate DataType="{x:Type MyAssembly:Customer}">
<StackPanel>
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Address}" />
</StackPanel>
</DataTemplate>
这样,当我打开我的 ComboBox 时,我可以看到不同的客户及其姓名,以及在其下方的地址。
但是当我选择一个客户时,我只想在组合框中显示名称。比如:
<DataTemplate DataType="{x:Type MyAssembly:Customer}">
<StackPanel>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
我可以为 ComboBox 中的选定项目选择另一个模板吗?
解决方案
在答案的帮助下,我解决了这个问题:
<UserControl.Resources>
<ControlTemplate x:Key="SimpleTemplate">
<StackPanel>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</ControlTemplate>
<ControlTemplate x:Key="ExtendedTemplate">
<StackPanel>
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Address}" />
</StackPanel>
</ControlTemplate>
<DataTemplate x:Key="CustomerTemplate">
<Control x:Name="theControl" Focusable="False" Template="{StaticResource ExtendedTemplate}" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBoxItem}}, Path=IsSelected}" Value="{x:Null}">
<Setter TargetName="theControl" Property="Template" Value="{StaticResource SimpleTemplate}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</UserControl.Resources>
然后,我的组合框:
<ComboBox ItemsSource="{Binding Customers}"
SelectedItem="{Binding SelectedCustomer}"
ItemTemplate="{StaticResource CustomerTemplate}" />
让它工作的重要部分是Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBoxItem}}, Path=IsSelected}" Value="{x:Null}"(值应该是 x:Null,而不是 True 的部分)。
【问题讨论】:
-
您的解决方案有效,但在“输出”窗口中出现错误。
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ComboBoxItem', AncestorLevel='1''. BindingExpression:Path=IsSelected; DataItem=null; target element is 'ContentPresenter' (Name=''); target property is 'NoTarget' (type 'Object') -
我记得也看到过这些错误。但是我不再参与这个项目(甚至不在公司),所以我无法检查这个,抱歉。
-
DataTrigger 中没有必要提及绑定路径。当 ComboBoxItem 被选中时,将向控件应用不同的模板,并且 DataTrigger 绑定将不再能够在其元素树中找到类型为 ComboBoxItem 的祖先。因此,与 null 的比较将始终成功。这种方法之所以有效,是因为 ComboBoxItem 的可视化树会根据它是被选中还是显示在弹出窗口中而有所不同。