WPF Convert和RelativeSource
自定义Converter
后台Converter类实现接口IValueConverter
方法Convert是值->UI
方法ConvertBack是UI->值
初始化走Convert
public class ColorConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//value为当前的对象
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;
}
}
前端
前端引用命名空间,实例化静态资源
<converts:ColorConvert x:Key="MyConvert"></converts:ColorConvert>
将MyConvert绑定给Style
<Style x:Key="Item" TargetType="ListViewItem">
<!--表明将自身的背景颜色修改-->
<Setter Property="Background">
<Setter.Value>
<!--RelativeSource="{RelativeSource Self}"的Self不能用控件名称代替-->
<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
学习技术最好的文档就是【官方文档】,没有之一。
还有学习资料【Microsoft Learn】、【CSharp Learn】、【My Note】。
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的【推荐】按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。