none
datagrid如何指定某一行某一列的样式? RRS feed

  • 问题

  • 想做成下面的效果,第二行第二列的样式特殊。另外我的datagrid的列都是用代码生成的,不是用xmal,要如何实现下面的样式

    1-1 1-2 1-3
    2-1 2-2 2-3
    3-1 3-2 3-3
    2011年5月30日 2:30

答案

  • 在WPF XAML和代码是可以相互转换的,不管是XAML出来的还是代码出来的,我们都可以在代码中去获得一个Cell的对象然后指定其特殊的样式。 怎么获得DataGrid中的一个Cell, 你可以参考下面的FAQ: http://social.msdn.microsoft.com/Forums/zh-CN/wpfzhchs/thread/e1907834-611e-4e38-a47f-650a42087207
    我根据你的描述,写了一个简单的例子,你看下:
     
     public partial class MainWindow : Window
     {
      public MainWindow()
      {
       InitializeComponent();
    
       DataGrid dg = new DataGrid();
       dg.Columns.Add(new DataGridTextColumn() { Header = "Column 1", Binding = new Binding("[0]") });
       dg.Columns.Add(new DataGridTextColumn() { Header = "Column 2", Binding = new Binding("[1]") });
       dg.Columns.Add(new DataGridTextColumn() { Header = "Column 3", Binding = new Binding("[2]") });
    
       dg.Items.Add(new Object[] { "1-1", "1-2", "1-3" });
       dg.Items.Add(new Object[] { "2-1", "2-2", "2-3" });
       dg.Items.Add(new Object[] { "3-1", "3-2", "3-3" });
    
       this.Content = dg;
    
       dg.Loaded += (o, e) =>
       {
        // Change the specific Cell style
        DataGridCell cell = GetCell(dg, 1, 1);
        cell.Background = Brushes.Red;
       };
      }
    
      private DataGridCell GetCell(DataGrid dg, int RowIndex, int ColumnIndex)
      {
       DataGridRow rowContainer = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(RowIndex);
       DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
       return (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(ColumnIndex);
      }
    
      private T GetVisualChild<T>(Visual parent) where T : Visual
      {
       T child = default(T);
       int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
       for (int i = 0; i < numVisuals; i++)
       {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
    
        if (child == null)
         child = GetVisualChild<T>(v);
        else
         break;
       }
       return child;
      }
    

    Sincerely,

    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年5月30日 6:10
    版主