WPF 示例自定义的 DataTemplateSelector

由于实际环境无法在这里直接运行代码,但我可以提供一个WPF中使用DataTemplateSelector根据数据类型动态选择显示控件的示例代码。请将此代码片段复制到您的WPF项目中,并确保已定义了对应的ViewModel和数据类型。

首先,定义两个简单的数据类:

csharp 复制代码
public class MyDataType1
{
    public string Property1 { get; set; }
}

public class MyDataType2
{
    public int Property2 { get; set; }
}

然后创建自定义的

DataTemplateSelector:

csharp 复制代码
using System.Windows;
using System.Windows.Controls;

public class MyTemplateSelector : DataTemplateSelector
{
    public DataTemplate Template1 { get; set; }
    public DataTemplate Template2 { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item is MyDataType1)
            return Template1;
        else if (item is MyDataType2)
            return Template2;
        else
            return base.SelectTemplate(item, container);
    }
}

在XAML中注册并使用这些模板:

xml 复制代码
<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:YourNamespace"> <!-- 替换为您的命名空间 -->

    <Window.Resources>
        <DataTemplate x:Key="Type1Template">
            <TextBlock Text="{Binding Property1}" Foreground="Red" />
        </DataTemplate>
        
        <DataTemplate x:Key="Type2Template">
            <TextBlock Text="{Binding Property2}" Foreground="Blue" />
        </DataTemplate>

        <local:MyTemplateSelector x:Key="MySelector">
            <local:MyTemplateSelector.Template1>
                <StaticResource ResourceKey="Type1Template" />
            </local:MyTemplateSelector.Template1>
            <local:MyTemplateSelector.Template2>
                <StaticResource ResourceKey="Type2Template" />
            </local:MyTemplateSelector.Template2>
        </local:MyTemplateSelector>
    </Window.Resources>

    <StackPanel>
        <ContentControl Content="{Binding YourDataType1Instance}" ContentTemplateSelector="{StaticResource MySelector}"/>
        <ContentControl Content="{Binding YourDataType2Instance}" ContentTemplateSelector="{StaticResource MySelector}"/>
    </StackPanel>
</Window>

最后,在对应的ViewModel或代码后置中设置数据上下文(DataContext),包含

YourDataType1Instance

YourDataType2Instance

实例。这样,当窗口加载时,ContentControl将会根据内容的数据类型自动应用相应的模板样式。

第二种方式:

当然,我可以为您提供一个简单的 WPF 示例程序,其中包含一个自定义的 DataTemplateSelector。以下是一个基本示例代码:

MainWindow.xaml:

xml 复制代码
<Window x:Class="DataTemplateSelectorExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataTemplateSelectorExample"
        Title="DataTemplateSelector Example" Height="350" Width="525">

    <Window.Resources>
        <DataTemplate x:Key="Template1">
            <TextBlock Text="Template 1" />
        </DataTemplate>

        <DataTemplate x:Key="Template2">
            <TextBlock Text="Template 2" />
        </DataTemplate>

        <local:CustomDataTemplateSelector x:Key="TemplateSelector" />
    </Window.Resources>

    <Grid>
        <ContentControl Content="{binding MyProperty}" ContentTemplateSelector="{StaticResource TemplateSelector}"/>
    </Grid>
</Window>

DataItem.cs:

csharp 复制代码
using System.Windows;

namespace DataTemplateSelectorExample
{
    public class DataItem : FrameworkElement
    {
        public string TemplateType
        {
            get { return (string)GetValue(TemplateTypeProperty); }
            set { SetValue(TemplateTypeProperty, value); }
        }

        public static readonly DependencyProperty TemplateTypeProperty =
            DependencyProperty.Register("TemplateType", typeof(string), typeof(DataItem), new PropertyMetadata(null));
    }
	
	public class DataItemA: DataItem
	{
		TemplateType = Template1;
	}
	
	public class DataItemB: DataItem
	{
		TemplateType = Template2;
	}
}

CustomDataTemplateSelector.cs:

csharp 复制代码
using System.Windows;
using System.Windows.Controls;

namespace DataTemplateSelectorExample
{
    public class CustomDataTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            if (item is string name)
            {
                switch (name)
                {
                    case "Template1":
                        return (DataTemplate)((FrameworkElement)container).FindResource("Template1");
                    case "Template2":
                        return (DataTemplate)((FrameworkElement)container).FindResource("Template2");
                }
            }
            return base.SelectTemplate(item, container);
        }
    }
}

在这个示例程序中,我们定义了两种不同的 DataTemplate (Template1 和 Template2),然后创建了一个 CustomDataTemplateSelector 类来根据 DataItem 的 TemplateType 属性选择相应的 DataTemplate。最后在 MainWindow.xaml 中使用 ContentControl 来展示 DataItem,并利用 TemplateSelector 来选择应用的 DataTemplate。

请注意,这只是一个简单的示例。在实际应用中,您可能需要根据实际需求来扩展和定制 DataTemplateSelector。希望这个示例能帮助您理解如何在 WPF 中使用 DataTemplateSelector。

一个数据模板示例:

xml 复制代码
<!-- MainWindow.xaml -->
<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <DataTemplate x:Key="TextTemplate">
            <TextBlock Text="{Binding Text}" />
        </DataTemplate>

        <DataTemplate x:Key="ImageTemplate">
            <Image Source="{Binding ImageSource}" Width="50" Height="50"/>
        </DataTemplate>

        <DataTemplate x:Key="DefaultTemplate">
            <TextBlock Text="No template available for this object type" />
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <ItemsControl ItemsSource="{Binding ModuleCollection}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ContentPresenter Content="{Binding}">
                        <ContentPresenter.ContentTemplate>
                            <DataTemplate>
                                <ContentControl Content="{Binding}">
                                    <ContentControl.Style>
                                        <Style TargetType="ContentControl">
                                            <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" />
                                            <Style.Triggers>
                                                <DataTrigger Binding="{Binding Type}" Value="Text">
                                                    <Setter Property="ContentTemplate" Value="{StaticResource TextTemplate}" />
                                                </DataTrigger>
                                                <DataTrigger Binding="{Binding Type}" Value="Image">
                                                    <Setter Property="ContentTemplate" Value="{StaticResource ImageTemplate}" />
                                                </DataTrigger>
                                            </Style.Triggers>
                                        </Style>
                                    </ContentControl.Style>
                                </ContentControl>
                            </DataTemplate>
                        </ContentPresenter.ContentTemplate>
                    </ContentPresenter>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</Window>
相关推荐
Scout-leaf4 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
柒.梧.6 天前
基于SpringBoot+JWT 实现Token登录认证与登录人信息查询
wpf
十月南城9 天前
Flink实时计算心智模型——流、窗口、水位线、状态与Checkpoint的协作
大数据·flink·wpf
听麟12 天前
HarmonyOS 6.0+ 跨端会议助手APP开发实战:多设备接续与智能纪要全流程落地
分布式·深度学习·华为·区块链·wpf·harmonyos
@hdd12 天前
Kubernetes 可观测性:Prometheus 监控、日志采集与告警
云原生·kubernetes·wpf·prometheus
zls36536512 天前
C# WPF canvas中绘制缺陷分布map
开发语言·c#·wpf
专注VB编程开发20年12 天前
c#Redis扣款锁的设计,多用户,多台电脑操作
wpf
闲人编程13 天前
定时任务与周期性调度
分布式·python·wpf·调度·cron·定时人物·周期性
zls36536513 天前
C# WPF canvas中绘制缺陷分布map并实现缩放
开发语言·c#·wpf
数据知道14 天前
PostgreSQL:Citus 分布式拓展,水平分片,支持海量数据与高并发
分布式·postgresql·wpf