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,而且实现的方式看上去比较优雅。
很自然的想到了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,而且实现的方式看上去比较优雅。
相关文章推荐
- WPF:DataTemplateSelector设置控件不同的样式
- DataTemplateSelector 设置控件不同的样式
- WPF中自定义的DataTemplate中的控件,在Window_Loaded事件中加载机制初探
- WPF 点击 datatemplate 里面的控件,获取相应绑定的数据
- selector和shape结合设置控件样式
- WPF 深入浅出 模板(DataTemplate 数据外衣、ControlTemplate 控件外衣、ItemsPanelTemplate 项布局
- 菲佣WPF——4(关于DataTemplate(2)动态控件添加神器)
- 继续聊WPF——设置网格控件列标题的样式
- 继续聊WPF——设置网格控件列标题的样式
- WPF silverlight获取子控件(获取DataTemplate里的子控件)
- 潜移默化学会WPF(转载篇<一>)--WPF 遍历DataTemplate(获取所有控件)
- 继续聊WPF——设置网格控件列标题的样式
- [WPF系列]-数据邦定之DataTemplate 对 ItemsControl 进行样式和模板处理
- WPF的DataGrid控件——分组、改变成DataTreeGrid的样式
- wpf动态设置控件样式
- WPF 获取 ListView DataTemplate 中控件值
- WPF 遍历DataTemplate(获取所有控件)
- WPF 遍历DataTemplate(获取所有控件)
- C# WinForm开发系列之DataTimePicker控件显示月份的限制和关于DataTimePicker和monthCalendar的样式设置问题
- WPF中ComboBox控件显示的样式设置