【问题标题】:Dynamically load different UserControls based on object type via data binding in xaml通过 xaml 中的数据绑定基于对象类型动态加载不同的 UserControl
【发布时间】:2012-12-06 21:16:54
【问题描述】:

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

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

所以,给定三个类:

public class House : Building{}

public class Apartment : Building{}

public class Tent : Building{}

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

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

【问题讨论】:

    标签: wpf xaml data-binding


    【解决方案1】:

    您可以在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>
    

    【讨论】:

    • 甜蜜!这正是我需要的。不知道你可以绑定到数据源的类型。
    【解决方案2】:

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

    【讨论】:

    • 但是我已经有自定义的(高度复杂的)用户控件,其中包含大量代码。所以 DataTemplate 对我来说真的不起作用。
    • 所以只需声明包含适当 UserControl 的模板?
    猜你喜欢
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 2016-11-09
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多