在这个相当简单的问题上度过了最后几个小时,我还没有找到办法。我正在使用GridView
来显示一些数据,需要使用转换器对单元格值进行一些自定义。这是相关的XAML:
<ListView ItemsSource="{Binding SomeDataTable}">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=XXX, Converter={StaticResource MyConverter}}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
我需要写什么代替上面的XXX?
N.B。我不能在这里放置常量列名,因为这个DataTemplate将由GridView的所有列使用。我需要一种方法来引用当前单元格值,就像使用DisplayMemberBinding
时GridView的默认模板一样。
我找到了相关的帖子here,但这也没有任何正确的答案。
答案 0 :(得分:0)
一个选项是使用DisplayMemberBinding创建GridViewColumns,然后将TextBlock的样式定义为ListView的资源并在那里使用转换器。
鉴于我有一个人员列表的场景,我想根据人的年龄为所有单元格着色:
数据项:
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public Person(int age, string name)
{
Age = age;
Name = name;
}
}
在XAML中创建列:
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Age}" />
<GridViewColumn DisplayMemberBinding="{Binding Name}" />
</GridView>
</ListView.View>
根据年龄更改单元格背景的转换器:
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((int) value < 20)
{
return Brushes.LightBlue;
}
return Brushes.LightGreen;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
使用转换器:
<ListView.Resources>
<Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
<Setter Property="Background">
<Setter.Value>
<Binding Path="Age">
<Binding.Converter>
<local:MyConverter/>
</Binding.Converter>
</Binding>
</Setter.Value>
</Setter>
</Style>
</ListView.Resources>
<强>结果:强>
完整XAML:
<ListView x:Name="MyItems" Loaded="MyItems_OnLoaded">
<ListView.Resources>
<Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
<Setter Property="Background">
<Setter.Value>
<Binding Path="Age">
<Binding.Converter>
<local:MyConverter/>
</Binding.Converter>
</Binding>
</Setter.Value>
</Setter>
</Style>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Age}" />
<GridViewColumn DisplayMemberBinding="{Binding Name}" />
</GridView>
</ListView.View>
</ListView>