WPF将多个UserControl绑定到列表框

时间:2013-10-17 21:19:55

标签: c# wpf inheritance user-controls listbox

我有多个UserControls,我想在ListBox上显示它们 让我们假设我有一个Employee抽象UserControl,并且我有2个或更多UserControls,而不是像EmployEmployee和FactoryEmployee这样的Employees,我有不同的数据,但UserControl非常相似(相同的大小,几乎相同的字段),ViewModel我有一个抽象的EmployeeViewModel,AdministrativeEmployeeViewModel和FatoryEmployeeViewModel,在EmployeesView上我有ListBox和数据绑定,在EmployeesViewModel上有一个ICollection Employees

EmployeesView.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>

EmployeesViewModel.cs:

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

但是这显示了ListBox上的System.ItemTemplate而不是每种类型的Employee的UserControls

1 个答案:

答案 0 :(得分:3)

ListBox资源中定义两个DataTemplates:

<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;

AdministrativeEmployeeView:

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

FactoryEmployeeView:

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

结果:

enter image description here