首页 > 其他分享 >WPF 数据模板Data Template

WPF 数据模板Data Template

时间:2024-09-20 17:51:04浏览次数:8  
标签:Code 数据 lst Add Template new WPF Data public

数据模板 DataTemplate 

控件模板决定了数据的展示形式和用户体检,在软件UI设计中非常重要。同样数据的展示形式越来越多样化,正所谓:横看成岭侧成峰,远近高低各不同。同样的数据内容,在DataGrid中的展示是文本的列表形式,在ComboBox中是下拉框的形式。给数据披上外衣,将数据和形式解耦,是一种新的发展趋势。

1. DataGrid
a. 数据模板

DataGrid是可以自定义网格数据显示的控件,通过自定义显示的列模板,可以实现各式各样的展现方式。列定义如下:

DataGrid的列定义,通过Binding="{Binding Name}"的方式绑定属性,通过ElementStyle="{StaticResource one_center}"的方式绑定样式。

DataGrid预制了几种列展示数据的方式,如:DataGridTextColumn【文本】,DataGridCheckBoxColumn【复选框】,DataGridComboBoxColumn【下拉框】,DataGridHyperlinkColumn【链接】等,如果使用数据模板,则采用DataGridTemplateColumn进行定义。

UI示例如下所示:
<Window x:Class="WpfApp2.A1Window"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="数据模板示例" Height="450" Width="650">
    <Window.Resources>
        <Style x:Key="one_center" TargetType="TextBlock">
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
            <Setter Property="HorizontalAlignment" Value="Center"></Setter>
</Style>
        <Style x:Key="one_header" TargetType="DataGridColumnHeader">
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
            <Setter Property="HorizontalAlignment" Value="Center"></Setter>
            <Setter Property="HorizontalContentAlignment" Value="Center"></Setter>
            <Setter Property="BorderThickness" Value="0"></Setter>
</Style>
    </Window.Resources>
    <Grid>
        <DataGrid x:Name="one"  Margin="10" AutoGenerateColumns="False"  CanUserAddRows="False"  CanUserSortColumns="False" BorderThickness="0" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="姓名" Binding="{Binding Name}" Width="*" ElementStyle="{StaticResource one_center}" HeaderStyle="{StaticResource one_header}"  />
                <DataGridTextColumn Header="年龄" Binding="{Binding Age}" Width="*" ElementStyle="{StaticResource one_center}" HeaderStyle="{StaticResource one_header}"/>
                <DataGridTextColumn Header="性别" Binding="{Binding Sex}" Width="*" ElementStyle="{StaticResource one_center}" HeaderStyle="{StaticResource one_header}"/>
                <DataGridTextColumn Header="班级" Binding="{Binding Classes}" Width="*" ElementStyle="{StaticResource one_center}" HeaderStyle="{StaticResource one_header}"/>
                <DataGridTemplateColumn Header="操作" Width="*" HeaderStyle="{StaticResource one_header}">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
                                <Button x:Name="edit" Content="编辑" Width="60" Margin="3" Height="25"></Button>
                                <Button x:Name="delete" Content="删除" Width="60" Margin="3" Height="25"></Button>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

b. 后台数据绑定

后台数据绑定通过ItemsSource进行赋值,绑定的数据的属性名,要和DataGrid的列绑定数据的名称保持一致,如下所示:

namespace WpfApp2
{
    /// <summary>
    /// A1Window.xaml 的交互逻辑
    /// </summary>
    public partial class A1Window : Window
    {
        public A1Window()
        {
            InitializeComponent();
 
            List<Student> lst = new List<Student>();
            lst.Add(new Student() { Name = "张三", Age = 22, Sex = "男", Classes = "一班" });
            lst.Add(new Student() { Name = "李四", Age = 21, Sex = "男", Classes = "二班" });
            lst.Add(new Student() { Name = "王五", Age = 20, Sex = "女", Classes = "一班" });
            lst.Add(new Student() { Name = "刘大", Age = 19, Sex = "男", Classes = "三班" });
            lst.Add(new Student() { Name = "麻子", Age = 18, Sex = "男", Classes = "四班" });
            one.ItemsSource = lst;
        }
    }
 
 
    public class Student
    {
        public string Name { get; set; }
 
        public int Age { get; set; }
 
        public string Sex { get; set; }
 
        public string Classes { get; set; }
    }
}

2. ListBox和ComboBox
a. 数据模板

ListBox,ComboBox,均是包含可选择的项的列表,只是ListBox不需要下拉显示,ComboBox需要下拉显示。通过定义数据模板,可以丰富数据的展示形式。

通过ItemTemplate="{StaticResource item_template}"的形式,进行数据模板的绑定。如下所示:
<Window x:Class="WpfApp2.A2Window"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="数据模板示例" Height="450" Width="800">
    <Window.Resources>
        <DataTemplate x:Key="item_template">
            <StackPanel Orientation="Horizontal" Margin="5 ,0">
                <Border Width="10" Height="10" Background="{Binding Code}"></Border>
                <TextBlock Text="{Binding Code}" Margin="5,0" ></TextBlock>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <StackPanel Margin="3" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
            <ComboBox x:Name="one" Height="25" Width="120" Margin="5" ItemTemplate="{StaticResource item_template}"></ComboBox>
            <ListBox x:Name="two"  Width="120" Margin="5" ItemTemplate="{StaticResource item_template}"></ListBox>
        </StackPanel>
    </Grid>
</Window>
b. 后台数据绑定

与DataGrid一样,后台通过ItemsSource进行数据的绑定。如下所示:
namespace WpfApp2
{
    /// <summary>
    /// A2Window.xaml 的交互逻辑
    /// </summary>
    public partial class A2Window : Window
    {
        public A2Window()
        {
            InitializeComponent();
            List<Color> lst = new List<Color>();
            lst.Add(new Color() { Code = "#FE8C00" });
            lst.Add(new Color() { Code = "#1F7F50" });
            lst.Add(new Color() { Code = "#AA8C00" });
            lst.Add(new Color() { Code = "#FEAA00" });
            lst.Add(new Color() { Code = "#008CAA" });
            lst.Add(new Color() { Code = "#FEBB00" });
            one.ItemsSource = lst;
            two.ItemsSource = lst;
        }
    }
 
    public class Color
    {
        public string Code { get; set; }
    }
}

3. ItemsControl
a. 数据模板

ItemsControl,主要用于展示集合数据的项,也是列表控件的一种。ItemsControl 需要设置两个内容:

ItemsControl.ItemsPanel,做为数据展示的容器。

ItemsControl.ItemTemplate,用于单个数据的展示形式。

具体如下所示:

<Window x:Class="WpfApp2.A3Window"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="A3Window" Height="450" Width="800">
    <Grid>
        <ItemsControl x:Name="one">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel></WrapPanel>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Width="50" Height="50" Margin="5" Content="{Binding Code}"></Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</Window>
b. 后台数据绑定

与DataGrid一样,后台通过ItemsSource进行数据的绑定。如下所示:

 
namespace WpfApp2
{
    /// <summary>
    /// A3Window.xaml 的交互逻辑
    /// </summary>
    public partial class A3Window : Window
    {
        public A3Window()
        {
            InitializeComponent();
            List<Test> lst = new List<Test>();
            lst.Add(new Test() { Code = "1" });
            lst.Add(new Test() { Code = "2" });
            lst.Add(new Test() { Code = "3" });
            lst.Add(new Test() { Code = "4" });
            lst.Add(new Test() { Code = "5" });
            lst.Add(new Test() { Code = "6" });
            one.ItemsSource = lst;
        }
    }
 
    public class Test
    {
        public string Code { get; set; }
    }
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/weijia3624/article/details/135269199

 

标签:Code,数据,lst,Add,Template,new,WPF,Data,public
From: https://www.cnblogs.com/ywtssydm/p/18321043

相关文章

  • WPF 控件模板ControlTemplate
    <Button><Button.Template><ControlTemplate><Grid><EllipseName="faceEllipse"Width="{TemplateBindingButton.Width}"Height=&qu......
  • WPF 模板总结(Template)
    模板(Template):WPF系统不但支持传统的Winfrom编程的用户界面和用户体验设计,更支持使用专门的设计工具Blend进行专业设计,同时还推出了以模板为核心的新一代设计理念。在WPF中,通过引入模板(Template)微软将数据和算法的“内容”与“形式”解耦了。模板是算法和数据的外衣,决定了它们......
  • 解决jupyter删除文件时出现:send2trash failed: [Errno 13] Permission denied: b'/dat
    参考资料:https://github.com/jupyter-server/jupyter_server/issues/1338今天在使用自己部署的jupyterlab删除文件的时候出现了一个奇怪的报错:send2trashfailed:[Errno13]Permissiondenied:b'/data/.Trash-1383490'好家伙,删东西都不让我删。虽然如此,问题......
  • DAT 560G: Database Design and SQL
    DAT560G:DatabaseDesignand SQLFall2024,MiniAAssignment#3:SQL Part 2Instructions1. Thisisan individual assignment. Youmay not discussyour approachto solvingthese questions withanyone(orGenerativeAI),otherthantheinstructor......
  • WPF ScrollViewer.IsDeferredScrollingEnabled is true can enhance the performance
    Whenanitemscontrolisusingavirtualizingpanel anditcontainsalargenumberofcomplexitems,settingIsDeferredScrollingEnabledto truecanresultinasignificantperformanceimprovementbyavoidingtherenderingof intermediatestates.Applicati......
  • WPF DataGrid ItemsSource StaticResource
    //xaml<Windowx:Class="WpfApp386.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......
  • WPF behavior InvokeCommandAction CommadParameter pass selectedItem of currentcon
    <ListBoxx:Name="lbx"SelectedIndex="0"ItemsSource="{BindingBooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"VirtualizingPanel.IsContainerVirtualizable="True"......
  • WPF behavior InvokeCommandAction CommandParameter
    <ListBoxx:Name="lbx"SelectedIndex="0"ItemsSource="{BindingBooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"VirtualizingPanel.IsContainerVirtualizable="True"......
  • WPF behavior InvokeCommndAction PassEventArgsToCommand
    //xaml<ListBoxx:Name="lbx"SelectedIndex="0"ItemsSource="{BindingBooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"VirtualizingPanel.IsContainerVirtualizable="Tru......
  • DevExpress WinForms中文教程:Data Grid - 如何设置视图和列外观?
    本教程将带您了解用于更改网格元素外观的外观设置,在哪里可以找到视图或单个列的这些设置,以及如何更改视图的绘制样式,以便您可以自定义主题绘制的元素。P.S:DevExpressWinForms拥有180+组件和UI库,能为WindowsForms平台创建具有影响力的业务解决方案。DevExpressWinForms能完美构......