2011-08-16 66 views
1

每当用户单击按钮时,我想要获取DataGrid中的选定行并更改其背景色? 我可以使用SelectedIndex属性获取所选行的索引,但我不知道如何更改背景。在DataGrid中获取所选行并更改背景颜色

我在VS2010中使用WPF,C#和.Net 4。

谢谢...

回答

3

这是更好地使用触发器,这种事情,但请尝试以下

private void button_Click(object sender, RoutedEventArgs e) 
{ 
    DataGridRow dataGridRow = dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex) as DataGridRow; 
    if (dataGridRow != null) 
    { 
     dataGridRow.Background = Brushes.Green; 
    } 
} 

编辑
选定DataGridCells仍将会覆盖背景,因此你可能必须处理为好,使用在Tag财产上的父DataGridRow例如

<DataGrid ...> 
    <DataGrid.CellStyle> 
     <Style TargetType="DataGridCell"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, 
               Path=Tag}" Value="ChangedBackground"> 
        <Setter Property="Background" Value="Transparent" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </DataGrid.CellStyle> 
    <!--...--> 
</DataGrid> 

private void button_Click(object sender, RoutedEventArgs e) 
{ 
    DataGridRow dataGridRow = dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex) as DataGridRow; 
    if (dataGridRow != null) 
    { 
     dataGridRow.Background = Brushes.Green; 
     dataGridRow.Tag = "ChangedBackground"; 
    } 
} 
+0

谢谢......那个工作。 – Manoj

+0

@Manoj:很高兴听到:)不知道如果你需要更新的部分,但我补充说,以防万一.. –

+0

我使用相同的代码,但总是返回null与我任何想法请 –

2

试试这个

//get DataGridRow 
DataGridRow row = (DataGridRow)dGrid.ItemContainerGenerator.ContainerFromIndex(RowIndex); 
row.Background = Brushes.Red; 
+0

它总是返回null我任何想法,请帮助 –

+0

作品非常好!但是还有另一种清除默认颜色的方法吗? 我正在使用for循环来选择每个rowIndex。 :( – dll

0

DataGridRow有背景属性。这是你需要的吗?

0

你也可以使用这样的:

<DataGrid ...> 
<DataGrid.CellStyle> 
    <Style TargetType="DataGridCell"> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, 
              Path=IsSelected}" Value="true"> 
       <Setter Property="Background" Value="Transparent" /> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 
</DataGrid.CellStyle> 
<!--...--> 

+0

似乎是一个体面的答案可能是值得解释它在做什么。 – Peter