Reputation: 706
DataGrid.ItemSource
gets set in code behind to a dataview
. Column names and count needs to change on the fly, so a list of objects doesn't work very well.
I have the table display working completely correctly. Which is great, but my GridCellStyle passes the DataRowView to the converter, instead of the DataGridCell which is what I expected to pass.
Is there a way to either get the DataGridCell content OR something indicating which column is current passed to my converter?
<UserControl x:Class="TestUI.SilveusTable"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestUI"
mc:Ignorable="d"
>
<UserControl.Resources>
<local:CbotValueConverter x:Key="CbotValueConverter" />
<Style x:Key="GridCellStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Yellow"/>
<Setter Property="Foreground" Value="{Binding Converter={StaticResource CbotValueConverter}}"/>
</Style>
</UserControl.Resources>
<Grid>
<DataGrid x:Name="DataGrid1" IsReadOnly="True" CellStyle="{StaticResource GridCellStyle}" />
</Grid>
</UserControl>
Here is my Converter Class
[ValueConversion(typeof(DataGridCell), typeof(SolidColorBrush))]
public class CbotValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var dgc = (DataGridCell) value;
var rowView = (DataRowView) dgc.DataContext;
var v = rowView.Row.ItemArray[dgc.Column.DisplayIndex];
decimal amount;
if (decimal.TryParse(v.ToString(), out amount))
{
if (amount >= 10) return Brushes.Red;
if (amount >= 5) return Brushes.Blue;
if (amount > 0) return Brushes.Green;
}
return Brushes.Black; //quantity should not be below 0
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Upvotes: 3
Views: 691
Reputation: 35722
change the Source of a binding
with currect binding declaration, DataContext of DataGridCell is the Source
Value="{Binding Converter={StaticResource CbotValueConverter}}"
to use DataGridCell itself add RelativeSource Self
part (refers to the element on which you are setting the binding)
Value="{Binding Converter={StaticResource CbotValueConverter},
RelativeSource={RelativeSource Self}}"
Upvotes: 4