在 WPF 项目中,我有一个 ComboBox
可以从不同的对象中进行选择。使用 ItemsControl
及其 ItemTemplateSelector
我试图根据对象的属性为 ComboBox
选择显示不同的 UI。因此,在下面的示例中,我们从人物对象中进行选择。在 ItemTemplateSelector
中,我们根据 Person
的 IsManager
属性选择不同的 DataTemplate
。问题是它不起作用。
我怀疑这可能是由于 ItemsControl
的 ItemsSource
绑定(bind)到一个项目,但我不确定。如果这是问题所在,我可以对代码进行哪些更改来实现此目的?
XAML:
<Window x:Class="ItemsSelector.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ItemsSelector"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.Resources>
<local:Selector x:Key="selector"/>
<DataTemplate x:Key="managerTemplate">
<TextBlock Text="Manager"/>
</DataTemplate>
<DataTemplate x:Key="juniorTemplate">
<TextBlock Text="Junior"/>
</DataTemplate>
</Grid.Resources>
<ComboBox x:Name="cbo" Margin="2" Grid.Row="0" ItemsSource="{Binding .}" SelectedIndex="0">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ItemsControl Grid.Row="1" ItemTemplateSelector="{StaticResource selector}" ItemsSource="{Binding ElementName=cbo ,Path=SelectedItem}">
</ItemsControl>
</Grid>
背后的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Person[] {
new Person() { Name = "Boss", IsManager = true },
new Person() { Name = "Underling", IsManager = false }
};
}
}
人:
public class Person
{
public string Name { get; set; }
public bool IsManager { get; set; }
public string Title { get; set; }
}
选择器:
public class Selector : DataTemplateSelector
{
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is Person)
{
var person = item as Person;
switch (person.IsManager)
{
case true:
return element.FindResource("managerTemplate") as DataTemplate;
case false:
return element.FindResource("juniorTemplate") as DataTemplate;
default:
break;
}
}
return null;
}
}
最佳答案
ItemsControl
的 ItemsSource
属性只能绑定(bind)到返回 IEnumerable
的集合。
您应该使用 ContentControl
才能绑定(bind)显示 ComboBox
的所选项目:
<ContentControl Grid.Row="1" ContentTemplateSelector="{StaticResource selector}"
Content="{Binding ElementName=cbo ,Path=SelectedItem}">
</ContentControl>
关于c# - 如何让 ItemTemplateSelector 在 WPF 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42652506/