[WPF學習筆記] - Binding

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://stackoverflow.com/questions/7851066/wpf-datagrid-cell-background-using-binding
https://stackoverflow.com/questions/20993293/multidatatrigger-vs-datatrigger-with-multibinding

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章