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>
相关推荐
△曉風殘月〆16 小时前
WPF颜色(SolidColorBrush)和Win32颜色(COLOREF)互转的方法
wpf·win32·solidcolorbrush·colorref
shanshan209920 小时前
上位机系统架构 | 如何设计一个高效的多相机管理系统
c#·wpf·相机
充值内卷1 天前
WPF入门教学四 WPF控件概述
windows·ui·wpf
小白2 天前
WPF自定义Dialog模板,内容用不同的Page填充
wpf
Crazy Struggle2 天前
C# + WPF 音频播放器 界面优雅,体验良好
c#·wpf·音频播放器·本地播放器
James.TCG3 天前
WPF动画
wpf
He BianGu3 天前
笔记:简要介绍WPF中FormattedText是什么,主要有什么功能
笔记·c#·wpf
脚步的影子3 天前
.NET 6.0 + WPF 使用 Prism 框架实现导航
.net·wpf
jyl_sh4 天前
Ribbon (WPF)
ribbon·wpf·client·桌面程序开发·c/s客户端
wo63704314 天前
[Visual Stuidio 2022使用技巧]2.配置及常用快捷键
c#·.net·wpf