4

WPF 中是否有某种方式可以获得与DataTemplateSelector您相同的功能,但对于 UserControls?

假设我有一个 StackView,我想将一个 IEnumerable 对象绑定到该 StackView。我想做的是以某种方式有一个映射,对于绑定的 IEnumerable 中的每个对象类型,查看对象类型并确定要添加到 StackView 的 UserControl。

因此,给定三个类:

public class House : Building{}

public class Apartment : Building{}

public class Tent : Building{}

每个类都继承自Building并定义了自己的类UserControl,我想设置DataContext为 anIEnumerable<Building>并以某种方式让 StackView 使用特定于类型的 UserControl 填充其子集。

我想用尽可能少的代码来做到这一点。数据绑定和 XAML 管道磁带越多越好。

4

2 回答 2

7

您可以在 ; 中使用复杂的用户控件DataTemplate。只需声明DataTemplate为您的UserControl.

例子:

  <Window x:Class="WpfApplication4.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication4"
            Title="MainWindow" Height="300" Width="300" Name="UI" >
        <Window.Resources>
            <DataTemplate DataType="{x:Type local:House}" >
                <local:HouseUserControl DataContext="{Binding}"/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type local:Apartment}">
                 <local:ApartmentUserControl DataContext="{Binding}"/>
            </DataTemplate>
        </Window.Resources>

        <Grid>
            <ListBox ItemsSource="{Binding ElementName=UI, Path=ListOfBuildings}" />
        </Grid>
    </Window>
于 2012-12-06T21:47:11.950 回答
2

我不确定我是否看到了问题。只需在某处为资源中的每种类型创建 DataTemplates,WPF 就会自动使用它们来呈现每种类型。

于 2012-12-06T21:28:30.233 回答