一个
DataTemplateSelector
可以实现你想要的功能。你可以在用户控件的 XAML 中定义不同的模板,然后让选择器在它们之间进行选择。
假设这些是模型类:
public class Employee
{
public Employee(string fullName)
{
FullName = fullName;
}
public string FullName { get; }
}
public class Certifying
{
public Certifying(string certifyingAuthor, DateTime certifyingDate)
{
CertifyingAuthor = certifyingAuthor;
CertifyingDate = certifyingDate;
}
public string CertifyingAuthor { get; }
public DateTime CertifyingDate { get; }
}
你的用户控件的XAML中有一个ListBox
,它反过来使用了一个模板选择器(我们稍后会讲到)-- 并且为两种不同的模型类型定义了不同的模板:
<UserControl
x:Class="WPF.UserControl1"
xmlns="http:
xmlns:x="http:
xmlns:local="clr-namespace:WPF"
>
<Grid>
<ListBox x:Name="listBox">
<ListBox.ItemTemplateSelector>
<local:MyTemplateSelector>
<local:MyTemplateSelector.EmployeeTemplate>
<DataTemplate DataType="local:Employee">
<TextBlock
Foreground="Red"
Text=""
/>
</DataTemplate>
</local:MyTemplateSelector.EmployeeTemplate>
<local:MyTemplateSelector.CertifyingTemplate>
<DataTemplate DataType="local:Certifying">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock
Foreground="Blue"
Text=""
/>
<TextBlock
Grid.Column="1"
Foreground="Green"
Text=""
/>
</Grid>
</DataTemplate>
</local:MyTemplateSelector.CertifyingTemplate>
</local:MyTemplateSelector>
</ListBox.ItemTemplateSelector>
</ListBox>
</Grid>
</UserControl>
用户控件的代码后台,我只是将一个模型对象列表分配给列表框(为了简单起见):
public partial class UserControl1
{
public UserControl1()
{
InitializeComponent();
listBox.ItemsSource = new List<object>
{
new Employee("Donald Duck"),
new Certifying("Mickey Mouse", DateTime.Now),
new Employee("Napoleon Bonaparte"),
new Certifying("Homer Simpson", DateTime.Now - TimeSpan.FromDays(2)),
};
}
}
最后,是模板选择器。它的两个属性是从用户控件的XAML中设置的;
SelectTemplate
的逻辑决定应用哪一个:
public class MyTemplateSelector : DataTemplateSelector
{
public DataTemplate EmployeeTemplate { get; set; }
public DataTemplate CertifyingTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item is Employee)
{
return EmployeeTemplate;
}
if (item is Certifying)
{
return CertifyingTemplate;
}
return base.SelectTemplate(item, container);
}
}
为了完整起见,使用用户控件:
<Grid>
<wpf:UserControl1 />
</Grid>
最终结果是拿破仑当前被选择,而荷马遭受悬停影响:
DataTemplate.TargetType
进行操作。https://msdn.microsoft.com/zh-cn/library/system.windows.controls.datatemplateselector(v=vs.110).aspx - Mat