2016-11-29 3 views
1

DataGrid.ItemSourceはコードの後ろにdataviewに設定されます。列の名前と数をオンザフライで変更する必要があるため、オブジェクトのリストがうまく機能しません。ConverterはDataGridCellの代わりにDataRowViewを取得します

テーブルの表示が完全に正しく動作しています。これは素晴らしいです、しかし、私のGridCellStyleは、私が渡す予定のDataGridCellではなく、DataRowViewをコンバータに渡します。

DataGridCellのコンテンツを取得する方法はありますかまたは現在の変換元にどの列が渡されているかを示すものはありますか?ここで

<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> 

私のコンバータクラス

[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(); 
     } 
    } 
+0

"これは私が期待していたものです。"それは間違った期待です。バインディングソース(Source、RelativeSource、ElementName)を明示的に設定しない限り、Bindingは現在のDataContextをソースとして使用します。これは、ItemsまたはItemsSourceコレクションの現在の要素です。 – Clemens

+0

スタイルが* DataGridCell *にバインドされていて、タグが* CellStyle *であるとすれば、バインダーがコンバーターにバインドされていることを想定すると、非常に合理的な期待のようです。セルの内容に基づいて変換を実行するにはどうすればよいですか? –

+0

スタイルは何にも束縛されません。スタイルのプロパティBindingが明示的に別のソースを指定しない限り、Setterは現在のDataContextのプロパティにバインドできます。それ以外にも、セルの内容はDataGridCellではありません。ここをクリックしてください:[データテンプレートの概要](https://msdn.microsoft.com/en-us/library/ms742521(v = vs.110).aspx) – Clemens

答えて

2

currectバインディング宣言変化結合

のソース、DataGridCellのDataContextのは、Source

Value="{Binding Converter={StaticResource CbotValueConverter}}" 

DataGridCellを使用することですそれ自体はRelativeSource Self部分を追加します(あなたがバインディングを設定しています)。

Value="{Binding Converter={StaticResource CbotValueConverter}, 
       RelativeSource={RelativeSource Self}}" 
関連する問題