您的位置:首页 > Web前端 > CSS

WPF:DataTemplateSelector设置控件不同的样式

2012-08-23 23:25 513 查看
最近想实现这么个东西,一个ListBox, 里面的ListBoxItem可能是文本框、下拉框、日期选择控件等等。

很自然的想到了DataTemplateSelector,并且事先定义好各类DataTemplate以显示不同的控件。

先定义好各类资源

SelectTemplate V2

public override DataTemplate SelectTemplate(object item, DependencyObject container)

{

Type t = item.GetType();

Type controlType = null;

PropertyInfo[] properties = t.GetProperties();

foreach (PropertyInfo pi in properties)

{

if (pi.PropertyType == typeof(Type))

{

controlType = (Type)pi.GetValue(item, null);

break;

}

}

if (controlType == typeof(TextBox))

{

return TextBoxTemplate;

}

if (controlType == typeof(ComboBox))

{

return ComboBoxTemplate;

}

if (controlType == typeof(DatePicker))

{

return DateTimeTemplate;

}

return null;

}

这样,要显示不同的控件,在ControlType里面定义即可,然后在XAML添加DataTemplate,在DataTemplateSelector对象中根据不同的ControlType返回不同的DataTemplate,而且实现的方式看上去比较优雅。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: