ebelair ebelair - 2 months ago 40
C# Question

Datagrid cell style with converterParameter

How to use converterParameter in a style setter on a datagrid cell?
I need to know the element name or property name in my converter.

xaml:

<Window.Resources>
<view:IsEnabledCellConverter x:Key="IsEnabledCellConverter"/>
<Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="IsEnabled"
Value="{Binding
Path=Item,
Converter={StaticResource ResourceKey=IsEnabledCellConverter},
ConverterParameter={?????}}"
RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}} />
</Style>
.../...

<Datagrid>
<DataGrid.Columns>
<DataGridTextColumn x:Name="Design"
CellStyle="{StaticResource CellStyle}"
Value="{Binding Path=Design}"/>
<DataGridTextColumn x:Name="FooBar"
CellStyle="{StaticResource CellStyle}"
Value="{Binding Path=Foobar}"/>
</DataGrid.Columns>
</Datagrid>


Converter class:

class IsEnabledCellConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string p = (string)parameter;
MyItem item = (MyItem)value;

switch (p)
{
case "Design":
return string.IsNullOrEmpty(item.Reference);
break;
case "FooBar":
return item.Something != true;
break;
default:
return true;
}
}

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


EDIT: I added some detail for understanding the needs.
So all my columns IsEnabled props are binding this global Converter for two reasons:


  1. it's easier to maintain

  2. some column need to be enabled depending of the value of other item values.


Answer

You should use DisplayIndex or Header, and set ConverterParameter accordingly.

<Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource Self}}" Value="0">
            <Setter Property="IsEnabled" 
                    Value="{Binding 
                            Path=Item,
                            Converter={StaticResource ResourceKey=IsEnabledCellConverter}, 
                            ConverterParameter=0,
                            RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource Self}}" Value="1">
            <Setter Property="IsEnabled" 
                    Value="{Binding 
                            Path=Item,
                            Converter={StaticResource ResourceKey=IsEnabledCellConverter}, 
                            ConverterParameter=1,
                            RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

Please tell if this solves your problem.