特定数据类型的特定控件 [英] Specific control for a specific DataType
问题描述
我有一个包含不同类型对象的列表:
I have a List which contains different types of objects:
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
中看到它们.例如:DatePicker
表示DateTime
,TextBlock
表示string
,TextBox
表示Person
的名称和姓氏...
I want to see them in a ListBox
with different kinds of controls. For instance: DatePicker
for DateTime
, TextBlock
for string
, TextBox
for Person
's Name and LastName...
是否可以通过XAML
执行此任务?
Is it possible to do this task with XAML
?
帮助表示赞赏.
推荐答案
<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;
}
}
结果:
如您所见,完全没有理由使用在WPF中使用代码来操作UI元素(某些非常特殊的情况除外)
As you can see, there's no reason at all to use code to manipulate UI elements in WPF (except some very very specific cases)
请注意,通常不会为System
命名空间内的类(例如System.String
)创建DataTemplate
.这仅是一个示例.如果确实需要,则可能必须创建每种类型的ViewModel
.
Note that you don't usually create a DataTemplate
for classes inside the System
namespace (such as System.String
. This is only to give you an example. If you really needed this you would probably have to create a ViewModel
for each type.
这篇关于特定数据类型的特定控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!