2013-08-16 35 views
4

我试图改变DataGrid组合框列的ElementStyle。假设控件没有被编辑时,样式确实是TextBlock类型。因此,如在其他的例子,我已经试过:WPF中的DataGridComboBoxColumn的ElementStyle错误

<DataGridComboBoxColumn.ElementStyle> 
    <Style TargetType="TextBlock"> 
     <Setter Property="Background" Value="Green" /> 
    </Style> 
</DataGridComboBoxColumn.ElementStyle> 

当这个被嵌入在我DataGridComboBoxColumn的定义,我得到这个奇怪的错误消息:

“的TextBlock” TargetType的不匹配的类型元素'TextBlockComboBox'。

究竟是什么TextBlockComboBox?或者更重要的是,我怎样才能达到ElementStyle,因为定位ComboBox似乎没有做任何事情。

回答

2

ElementStyle在这种情况下应该是ComboBox的类型。我们有两种类型的DataGrid,它在运行 - DataGridRowDataGridCell,第一行是第二个单元格。因此,默认情况下,所有内容都由类型DataGridCell而不是TextBlock's的单元组成。

要确定另一列的类型,请使用DataGridTemplateColumn。因此DataGridComboBoxColumn可能定义为:

<DataGridTemplateColumn Width="1.5*" IsReadOnly="False" Header="Position2"> 
    <DataGridTemplateColumn.CellTemplate> 
     <DataTemplate> 
      <ComboBox x:Name="ComboBoxColumn" /> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn> 

使用此设置可以是任何类型的控件。

在你的情况,你需要创建一个样式DataGridCell

<Style x:Key="StyleForCell" TargetType="{x:Type DataGridCell}"> 
    <Setter Property="Background" Value="Green" /> 
</Style> 

而且使用这样的:

<DataGridComboBoxColumn x:Name="ComboBoxColumn" 
         CellStyle="{StaticResource StyleForCell}" 
         Header="Position" 
         SelectedItemBinding="{Binding Position}" /> 
+1

使用'TemplateColumn'工程,所以我会将其标记为答案。我仍然不明白为什么我的代码失败,因为它来自另一个网络解决方案。但我需要一个解决方案:) – Tekito

3

TextBlockComboBox是一个内部类型DataGridComboBoxColumn。我也不知道如何获得这种类型的风格,但你可以通过使用ComboBox风格,看起来欺骗DataGridComboBoxColumn.ElementStyleTextBlock

<Style x:Key="TextBlockComboBoxStyle" 
     TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type ComboBox}"> 
       <TextBlock Text="{TemplateBinding Text}" 
          Style="{StaticResource {x:Type TextBlock}}" /> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

在上面的风格我使用的是全局定义TextBlock风格别处定义和绑定ComboBoxText属性。最后,你可以使用样式像这样:

<DataGridComboBoxColumn ElementStyle="{StaticResource TextBlockComboBoxStyle}" 
         EditingElementStyle="{StaticResource {x:Type ComboBox}}" /> 

在这种情况下,EditingElementStyle又是别处定义的全局定义ComboBox风格。