ItemTemplateSelector 数据源选择器,控件模板选择器
背景:GridView、ListBox中的数据,如果需要不同的数据显示不同的模板,这个时候适合使用ItemTemplateSelector
1、window.Resources中定义两个数据模板,同一个数据集合,不同的数据使用不同的数据模板
<DataTemplate x:Key="yourDataTemp">
<DataTemplate.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="20" />
</Style>
</DataTemplate.Resources>
<Border
x:Name="border"
Margin="5"
Padding="5"
BorderBrush="Red"
BorderThickness="1">
<DockPanel HorizontalAlignment="Center">
<TextBlock Text="{Binding Path=name}" />
<TextBlock>!</TextBlock>
</DockPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="myDataTemp">
<WrapPanel Name="wrapPanel1" Orientation="Vertical">
<WrapPanel.Style>
<Style TargetType="WrapPanel">
<Setter Property="Background" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=id}" Value="1">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</WrapPanel.Style>
<TextBlock Text="{Binding Path=id}" />
<TextBlock Text="{Binding Path=name}" />
</WrapPanel>
<!--<DataTemplate.Triggers>
-->
<!-- 设置一下id为1的时候又干嘛 -->
<!--
<DataTrigger Binding="{Binding Path=id}" Value="1">
<Setter TargetName="wrapPanel1" Property="Background" Value="red"/>
</DataTrigger>
</DataTemplate.Triggers>-->
</DataTemplate>
-- 这里使用Student集合,属性有id和name
2、创建一个新的类重写SelectTemplate
// 接上DataTemplateSelector接口
public class dataTemplateSelector : DataTemplateSelector
{
// 重写方法
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item != null)
{
Student student = item as Student;
int taskitem = student.id;
var window = Application.Current.MainWindow;
if (taskitem == 1)
return window.FindResource("yourDataTemp") as DataTemplate;
else
return window.FindResource("myDataTemp") as DataTemplate;
}
MessageBox.Show("没有模板啊");
return null;
}
}
在window.Resources中引入该类
<local:dataTemplateSelector x:Key="myDataTemplateSelector" />
3、在ListView中原本的DataTemplate替换为ItemTemplateSelector
<ListBox
Width="300"
Margin="10"
HorizontalContentAlignment="Stretch"
ItemTemplateSelector="{StaticResource myDataTemplateSelector}"
ItemsSource="{Binding Source={StaticResource myData}}" />
原文地址:https://blog.csdn.net/weixin_46407807/article/details/136543651
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!