自定義Converter
后臺(tái)Converter類(lèi)實(shí)現(xiàn)接口IValueConverter
方法Convert是值->UI
方法ConvertBack是UI->值
初始化走Convert
public class ColorConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//value為當(dāng)前的對(duì)象
var item = value as ListViewItem;
var view = ItemsControl.ItemsControlFromItemContainer(item);
var index = view.ItemContainerGenerator.IndexFromContainer(item);
var data = view.Items[index] as Student;
if (data.Age == 22)
return Brushes.Red;
if (data.Age % 2 == 0)
return Brushes.Pink;
else
return Brushes.DeepSkyBlue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
前端
前端引用命名空間禀苦,實(shí)例化靜態(tài)資源
<converts:ColorConvert x:Key="MyConvert"></converts:ColorConvert>
將MyConvert綁定給Style
<Style x:Key="Item" TargetType="ListViewItem">
<!--表明將自身的背景顏色修改-->
<Setter Property="Background">
<Setter.Value>
<!--RelativeSource="{RelativeSource Self}"的Self不能用控件名稱(chēng)代替-->
<Binding RelativeSource="{RelativeSource Self}" Converter="{StaticResource MyConvert}"></Binding>
</Setter.Value>
</Setter>
</Style>
使用Style
<!--使用ItemContainerStyle將Style賦給ListView-->
<ListView ItemsSource="{Binding }" ItemContainerStyle="{StaticResource Item}">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="姓名" DisplayMemberBinding="{Binding Name}"></GridViewColumn>
<GridViewColumn Header="年齡" DisplayMemberBinding="{Binding Age}"></GridViewColumn>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
示例代碼
https://github.com/zLulus/NotePractice/tree/dev3/WPF/WpfDemo/Converts