在WPF中,我需要根据与此数据网格中其他行的比较为dataGridRow添加边框。
我无法更改源项属性,因此我想使用转换器来设置与条件匹配的行样式。
如何将当前用作DataGrid ItemsSource的ObservableCollection作为converterParameter传递给转换器?
<DataGrid ItemsSource="{Binding TableItems}" Name="TableDataGrid" AutoGenerateColumns="False" BorderThickness="0">
<DataGrid.ItemContainerStyle>
<Style TargetType="DataGridRow">
<Setter Property="BorderBrush" Value="#FF9E9E9E"/>
<Setter Property="BorderThickness" Value="{Binding Path=., Converter={StaticResource converter}, ConverterParameter= ??? }"/>
</Style>
</DataGrid.ItemContainerStyle>
<DataGrid.Columns>
...
</DataGrid.Columns>
</DataGrid>
从上面的示例代码中,我想将TableItems作为ConverterParameter传递。
答案 0 :(得分:2)
由于您无法绑定绑定的ConverterParameter
属性,因此应使用MultiBinding
并使转换器实现IMultiValueConverter
。
<Setter Property="BorderThickness">
<Setter.Value>
<MultiBinding Converter="{StaticResource converter}">
<Binding Path="."/>
<Binding Path="DataContext.TableItems"
RelativeSource="{RelativeSource AncestorType=DataGrid}"/>
</MultiBinding>
</Setter.Value>
</Setter>
答案 1 :(得分:2)
您无法将任何内容绑定到ConverterParameter
属性,因为它不是依赖项属性。
您可以使用带有多个输入值的IMultiValueConverter:
<DataGrid.ItemContainerStyle>
<Style TargetType="DataGridRow">
<Setter Property="BorderBrush" Value="#FF9E9E9E"/>
<Setter Property="BorderThickness">
<Setter.Value>
<MultiBinding Converter="{StaticResource multiConverter}">
<Binding Path="." />
<Binding Path="DataContext.TableItems" RelativeSource="{RelativeSource AncestorType=DataGrid}" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.ItemContainerStyle>
或者您可以向转换器添加depenendency属性并将此属性绑定到DataGrid
的ItemsSource集合:
public class DataGridConverter : DependencyObject, IValueConverter
{
public static readonly DependencyProperty SourceCollectionProperty =
DependencyProperty.Register("SourceCollection", typeof(IEnumerable),
typeof(DataGridConverter), new FrameworkPropertyMetadata(null));
public IEnumerable SourceCollection
{
get { return (IEnumerable)GetValue(SourceCollectionProperty); }
set { SetValue(SourceCollectionProperty, value); }
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<DataGrid ItemsSource="{Binding TableItems}" Name="TableDataGrid" AutoGenerateColumns="False" BorderThickness="0">
<DataGrid.Resources>
<local:DataGridConverter x:Key="converter" SourceCollection="{Binding Path=DataContext.TableItems, Source={x:Reference TableDataGrid}}" />
</DataGrid.Resources>
<DataGrid.ItemContainerStyle>
<Style TargetType="DataGridRow">
<Setter Property="BorderBrush" Value="#FF9E9E9E"/>
<Setter Property="BorderThickness" Value="{Binding Path=., Converter={StaticResource converter}}"/>
</Style>
</DataGrid.ItemContainerStyle>
</DataGrid>