前言
例如:根据网上了解和学习,整理了对WPF中DataTemplate的理解
一、DataTemplate含义
DataTemplate是模板(Template)中的一类,,控件可引用DataTemplate即可实现对同一模板数据的动态显示
二、实现步骤
1.新建类
定义数据类型,如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.Models
{
/// <summary>
///
/// </summary>
internal class TestModel
{
/// <summary>
/// 名称
/// </summary>
public string TestName { get; set; }
/// <summary>
/// 值
/// </summary>
public int TestValue { get; set; }
}
}
2.新建视图模型
实现数据初始化与变化监控,如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfApp1.Models;
namespace WpfApp1.ViewModels
{
internal class MainWindowVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public MainWindowVM()
{
#region 初始化数据
TestModelList = new List<TestModel>();
TestModelList.Add(new TestModel { TestName = "111", TestValue = 1 });
TestModelList.Add(new TestModel { TestName = "222", TestValue = 2 });
TestModelList.Add(new TestModel { TestName = "333", TestValue = 3 });
TestModelList.Add(new TestModel { TestName = "4444", TestValue = 4 });
TestModelList.Add(new TestModel { TestName = "555", TestValue = 5 });
TestModelList.Add(new TestModel { TestName = "666", TestValue = 6 });
#endregion
}
#region 变量变化
/// <summary>
///
/// </summary>
private List<TestModel> _TestModelList;
/// <summary>
/// 监控数据
/// </summary>
public List<TestModel> TestModelList
{
get { return _TestModelList; }
set
{
_TestModelList = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("TestModelList"));
}
}
}
#endregion
}
}
代码编写完后,主界面MainWindow需要绑定MainWindowVM,如下:
/// <summary>
/// 视图模型
/// </summary>
MainWindowVM mainWindowVM = new MainWindowVM();
public MainWindow()
{
InitializeComponent();
this.DataContext = mainWindowVM;
}
3.前端实现
代码与效果如下:
<GroupBox>
<ItemsControl ItemsSource="{Binding TestModelList}" VerticalAlignment="Center">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="4"></UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,5">
<TextBlock Text="{Binding TestName}" FontSize="16" Foreground="Black" Margin="0,5"></TextBlock>
<TextBlock Text="{Binding TestValue}" FontSize="10" Foreground="Green" Margin="0,5"></TextBlock>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</GroupBox>