2017-05-23 15 views
0

DataGridCellの値をForegroundプロパティコンバーターに渡すにはどうすればよいですか?c#DataGrid Cellの値をコンバータに渡すにはどうすればよいですか?

したがってGooglePositionConvertorは、Path =によって渡されたオブジェクトから作成された値を返します。私はGooglePositionConvertorによって返された値に基づいてセルスタイルの前景色を変更したいと思います。

<DataGridTextColumn Binding="{Binding Path=., Converter={StaticResource GooglePositionConvertor}}"> 
    <DataGridTextColumn.CellStyle> 
     <Style TargetType="{x:Type DataGridCell}"> 
      <Setter Property="Foreground" Value="{????????????, Converter={StaticResource ChangeBrushColour}}"/> 
     </Style> 
    </DataGridTextColumn.CellStyle> 
</DataGridTextColumn> 

答えて

1

バインディングパスを指定しないでください。フォアグラウンドプロパティは、バインディングソースとしてDataGridCellのDataContextを受け取ります。

<DataGrid ItemsSource="{Binding ColorList}" AutoGenerateColumns="False"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Binding="{Binding}"> 
      <DataGridTextColumn.CellStyle> 
       <Style TargetType="{x:Type DataGridCell}"> 
        <Setter Property="Foreground" Value="{Binding Converter={StaticResource ColorToBrush}}"/> 
       </Style> 
      </DataGridTextColumn.CellStyle> 
     </DataGridTextColumn> 
    </DataGrid.Columns> 
</DataGrid> 
+0

最初のコンバーター「GooglePositionConvertor」の行にバインドされたオブジェクトが必要ですが、そのセルの値はth e 2番目のコンバータ "ChangeBrushColour"。 – jamie

0
あなたは DataGridCellContentプロパティにバインドし、その Textプロパティが設定された後 TextBlockForegroundプロパティを設定できるように DependencyPropertyDescriptorを使用することができ

<DataGridTextColumn Binding="{Binding Path=., Converter={StaticResource GooglePositionConvertor}}"> 
    <DataGridTextColumn.CellStyle> 
     <Style TargetType="{x:Type DataGridCell}"> 
      <Setter Property="Foreground" Value="{Binding Path=Content, RelativeSource={RelativeSource Self}, 
       Converter={StaticResource ChangeBrushColour}}"/> 
     </Style> 
    </DataGridTextColumn.CellStyle> 
</DataGridTextColumn> 

public class Converter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     TextBlock content = value as TextBlock; 
     if(content != null) 
     { 
      string text = content.Text; 
      if(string.IsNullOrEmpty(text)) 
      { 
       DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, typeof(TextBlock)); 
       if (dpd != null) 
        dpd.AddValueChanged(content, OnTextChanged); 
      } 
      else 
      { 
       OnTextChanged(content, EventArgs.Empty); 
      } 
     } 
     return Binding.DoNothing; 
    } 

    private void OnTextChanged(object sender, EventArgs e) 
    { 
     TextBlock textBlock = sender as TextBlock; 
     string converterText = textBlock.Text; 
     //set foreground based on text... 
     textBlock.Foreground = Brushes.Violet; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 
関連する問題