WPF—DataTemplate

作者:追风剑情 发布于:2019-9-2 16:48 分类:C#

示例

MainWindow.xaml

  1. <Window
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:WpfTest"
  7. xmlns:Properties="clr-namespace:WpfTest.Properties"
  8. xmlns:wpf="http://schemas.microsoft.com/netfx/2007/xaml/presentation" x:Class="WpfTest.MainWindow"
  9. mc:Ignorable="d"
  10. Title="MainWindow" Height="250" Width="400">
  11. <!--资源通常定义在根节点,或者资源字典中-->
  12. <Window.Resources>
  13. <DataTemplate x:Key="myTaskTemplate">
  14. <Border Name="border" BorderBrush="Aqua" BorderThickness="1"
  15. Padding="5" Margin="5" Width="250">
  16. <StackPanel>
  17. <TextBlock Text="{Binding Path=TaskName}"/>
  18. <TextBlock Text="{Binding Path=Description}"/>
  19. <TextBlock Text="{Binding Path=Priority}"/>
  20. </StackPanel>
  21. </Border>
  22. </DataTemplate>
  23. </Window.Resources>
  24. <Grid>
  25. <ListBox Name="listBox" Width="300" Margin="10"
  26. ItemTemplate="{StaticResource myTaskTemplate}"/>
  27. </Grid>
  28. </Window>

MainWindow.xaml.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Data;
  8. using System.Windows.Documents;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using System.Windows.Navigation;
  13. using System.Windows.Shapes;
  14. using System.ComponentModel;//INotifyPropertyChanged
  15. using System.Threading.Tasks;
  16.  
  17. namespace WpfTest
  18. {
  19. /// <summary>
  20. /// MainWindow.xaml 的交互逻辑
  21. /// </summary>
  22. public partial class MainWindow : Window
  23. {
  24. public List<ItemData> myTodoList;
  25.  
  26. public MainWindow()
  27. {
  28. InitializeComponent();
  29.  
  30. List<ItemData> list = new List<ItemData>();
  31. list.Add(new ItemData { TaskName = "A", Description = "aaa", Priority = 1 });
  32. list.Add(new ItemData { TaskName = "B", Description = "bbb", Priority = 2 });
  33. list.Add(new ItemData { TaskName = "C", Description = "ccc", Priority = 3 });
  34. this.listBox.ItemsSource = list;
  35. }
  36. }
  37.  
  38. public class ItemData
  39. {
  40. // 注意:
  41. // 字段无法直接数据绑定
  42. // 只有属性才能与{Binding Path=*}绑定
  43. public string TaskName { get; set; }
  44. public string Description { get; set; }
  45. public int Priority { get; set; }
  46. }
  47. }

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号