2011-09-30 50 views
1

我有一個對象的數據網格。這些對象有一個名稱,一個「類型」屬性和一堆不相關的屬性。基於如果類型是「MaterialType」與否,我想設置樣式爲單元格文本塊(粗體&打算10px的)綁定樣式到DataGridTextColumns ElementStyle

我開始了一個轉換器。 =>它獲取類型並轉換爲字體權重。

<DataGridTextColumn.ElementStyle> 
    <Style TargetType="TextBlock"> 
     <Setter Property="FontWeight" Value="{Binding type, Converter={StaticResource ResourceKey=TypeToFontWeightConverter}}"/> 
     <Setter Property="Padding" Value="10,0,0,0"/> 
    </Style> 
</DataGridTextColumn.ElementStyle> 

它的工作..但我只能設置字體重量。

我想要個人風格。

所以我編輯我的轉換器轉換成TypeToStyle轉換

class TypeToStyleConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 

      Style style = new Style(typeof(TextBlock)); 

      if (value is Type && value == typeof(MaterialType)) 
      { 
       style.Setters.Add(new Setter(TextBlock.FontWeightProperty, FontWeights.Bold)); 
       style.Setters.Add(new Setter(TextBlock.PaddingProperty, new Thickness(0))); 
      } 
      else 
      { 
       style.Setters.Add(new Setter(TextBlock.FontWeightProperty, FontWeights.Bold)); 
       style.Setters.Add(new Setter(TextBlock.PaddingProperty, new Thickness(10,0,0,0))); 
      } 
      return style; 
     } 

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

     #endregion 
    } 

然後我轉換器進行綁定。

<DataGridTextColumn Binding="{Binding Name}" 
        Header="Name" 
        IsReadOnly="True" 
        Width="1*" 
        ElementStyle="{Binding type, Converter={StaticResource ResourceKey=TypeToStyleConverter}}"/> 

這一切都編譯好。但沒有風格。轉換器不會被觸發...

回答