特定DataType的特定控件

时间:2013-04-12 17:23:53

标签: wpf xaml listbox

我有一个包含不同类型对象的List:

    List<object> myList = new List<object>();
    DateTime date = DateTime.Now;
    myList.Add(date);
    int digit = 50;
    myList.Add(digit);
    myList.Add("Hello World");
    var person = new Person() { Name = "Name", LastName = "Last Name", Age = 18 };
    list.ItemsSource = myList;

    public class Person
    {
         public string Name { get; set; }
         public string LastName { get; set; }
         public int Age { get; set; }
    }

我希望在ListBox中看到它们具有不同类型的控件。例如:DatePickerDateTimeTextBlockstringTextBox为姓名和姓氏为Person ...

是否可以使用XAML执行此任务?

帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

<Window x:Class="MiscSamples.DataTemplates"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="DataTemplates"
        Height="300"
        Width="300">
  <Window.Resources>

    <!-- DataTemplate for strings -->
    <DataTemplate DataType="{x:Type sys:String}">
      <TextBox Text="{Binding Path=.}" />
    </DataTemplate>

    <!-- DataTemplate for DateTimes -->
    <DataTemplate DataType="{x:Type sys:DateTime}">
      <DataTemplate.Resources>
        <DataTemplate DataType="{x:Type sys:String}">
          <TextBlock Text="{Binding Path=.}" />
        </DataTemplate>
      </DataTemplate.Resources>
      <DatePicker SelectedDate="{Binding Path=.}" />
    </DataTemplate>


    <!-- DataTemplate for Int32 -->
    <DataTemplate DataType="{x:Type sys:Int32}">
      <Slider Maximum="100"
              Minimum="0"
              Value="{Binding Path=.}"
              Width="100" />
    </DataTemplate>
  </Window.Resources>
  <ListBox ItemsSource="{Binding}" />
</Window>

代码背后:

 public partial class DataTemplates : Window
    {
        public DataTemplates()
        {
            InitializeComponent();

            var myList = new List<object>();
            myList.Add(DateTime.Now);
            myList.Add(50);
            myList.Add("Hello World");

            DataContext = myList;
        }
    }

结果:

enter image description here

正如您所看到的,没有理由完全使用代码来操作WPF中的UI元素(除了一些非常特殊的情况)

修改:

请注意,您通常不会为DataTemplate命名空间内的类创建System(例如System.String。这只是为了给您一个示例。如果您真的需要这个您可能需要为每种类型创建ViewModel