欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【C#】WPF的Binding学习笔记

程序员文章站 2022-04-05 15:22:46
...
DataGrid cell background using binding

Datagrid单元格背景色绑定操作。

public class MyColor
{
    Brush Background { get; set; }
    bool UseColor {get; get;}
    int Percentage { get; set; }
}

// XAML
<DataGridTextColumn Header="xxx" Binding="{Binding MyColor.Percentage}">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="Background" Value="{Binding MyColor.Background}"/>
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

如果希望绑定的字段不是Brush而是其他类型,如int,bool,string等,则需要使用IValueConverter接口实现。

public class YourConverter : IValueConverter
{
	public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
	{
		if (value is bool)
		{
			if ((bool)value)
			{
				return Brushes.Orange;
			}
			else
			{
				return new SolidColorBrush() { Opacity = 0 };
			}
		}
		return Brushes.White;
	}

	public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
	{
		throw new NotImplementedException();
	}
}

// XAML
<Window.Resources>
	<converter1:SelectedBackgroundConverter x:Key="SelectedConverter"/>
</Window.Resources>

<DataGridTextColumn Header="xxx" Binding="{Binding MyColor.Percentage}">
	<DataGridTextColumn.CellStyle>
		<Style TargetType="DataGridCell">
			<Setter Property="VerticalAlignment" Value="Center"/>
			<Setter Property="HorizontalAlignment" Value="Center"/>
			<Setter Property="Foreground" Value="Black"/>
			<Setter Property="Background" Value="{Binding UseColor, Converter={StaticResource YourConverter}}"/>
		</Style>
	</DataGridTextColumn.CellStyle>
</DataGridTextColumn>

https://*.com/questions/7851066/wpf-datagrid-cell-background-using-binding
https://*.com/questions/20993293/multidatatrigger-vs-datatrigger-with-multibinding