1

我有多个 UserControl,我想在 ListBox 上显示它们让我们假设我有一个 Employee 抽象 UserControl,并且我有 2 个或更多 UserControl,而不是为每个员工使用该 Employee,例如 AdministrativeEmployee 和 FactoryEmployee 我有不同的数据,但 UserControl 非常类似(相同大小,几乎相同的字段),在 ViewModel 端我有一个抽象的 EmployeeViewModel、AdministrativeEmployeeViewModel 和 FatoryEmployeeViewModel,在EmployeesView 上我有带有数据绑定的ListBox,在EmployeesViewModel 我有一个ICollectionEmployees

雇员视图.xaml:

xmlns:local="clr-namespace:Solution.Controls"

-

    <ListBox ItemsSource={Binding Employees}>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding}" Name="Presenter" />
                <DataTemplate.Triggers>
                    <DataTrigger  Value="{x:Type local:AdministrativeEmployeeView}">
                        <Setter TargetName="Presenter" Property="Content">
                            <Setter.Value>
                                <local:AdministrativeEmployeeView />
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                    <DataTrigger Value="{x:Type local:FactoryEmployeeView}">
                        <Setter TargetName="Presenter" Property="Content">
                            <Setter.Value>
                                <local:FactoryEmployeeView/>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

员工视图模型.cs:

public ICollection<EmployeeViewModel> Employees { get; set; }

但这向我展示了 ListBox 上的 System.ItemTemplate 而不是每种员工类型的 UserControls

4

1 回答 1

5

ListBox资源中定义两个 DataTemplate:

<ListBox ItemsSource="{Binding Employees}">
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type local:AdministrativeEmployee}">
            <local:AdministrativeEmployeeView />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:FactoryEmployee}">
            <local:FactoryEmployeeView />
        </DataTemplate>
    </ListBox.Resources>            
</ListBox>

模型类:

public class Employee
{
    public string Name { get; set; }   
}

public class AdministrativeEmployee : Employee
{
}

public class FactoryEmployee : Employee
{
} 

样本数据:

List<Employee> _source = new List<Employee>();
_source.Add(new AdministrativeEmployee { Name = "A test1" });
_source.Add(new FactoryEmployee { Name = "F test1" });
_source.Add(new AdministrativeEmployee { Name = "A test2" });
_source.Add(new FactoryEmployee { Name = "F test2" });
Employees = _source;

行政雇员视图:

<UserControl ...>
    <Grid>
        <TextBlock Text="{Binding Name}" Background="Red" />
    </Grid>
</UserControl>

工厂员工视图:

<UserControl ...>
    <Grid>
        <TextBlock Text="{Binding Name}" Background="Green" />
    </Grid>
</UserControl>

结果:

在此处输入图像描述

于 2013-10-17T21:40:35.393 回答