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;
    }
}

前端

前端引用命名空间,实例化静态资源


将MyConvert绑定给Style


使用Style



    
        
            
                
                
            
        
    

示例代码

https://github.com/zLulus/NotePractice/tree/dev3/WPF/WpfDemo/Converts

你可能感兴趣的:(Convert和RelativeSource)