none
wpf dev后台如何设置选中行 RRS feed

全部回复

  • 你好,

    你可以在后台先设置DataGridRow的Style,并为其添加EventSetter事件,例如:

    <DataGrid.RowStyle>
                    <Style TargetType="DataGridRow">
                        <EventSetter Event="GotFocus" Handler="myDataGridMain_GotFocus" ></EventSetter>
                    </Style>
                </DataGrid.RowStyle>

    在后台就可以进行如下操作:

     private void myDataGridMain_GotFocus(object sender, RoutedEventArgs e)
            {
                //对列进行操作,比如改变选中行的背景
                DataGridRow row = sender as DataGridRow;
                row.Background = Brushes.Red;
            }

    当然,如果你不想在xaml中添加任何的style设置,你可以给DataGrid添加一个BeginningEdit事件,然后利用行号和列号来获取选中的单元格,然后对其进行修改,代码如下所示:

     private void myDataGridMain_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
            {
                int colindex = -1;
                int rowindex = -1;
                colindex = e.Column.DisplayIndex;
                rowindex = e.Row.GetIndex();
                DataGridRow row = (DataGridRow)myDataGridMain.ItemContainerGenerator.ContainerFromIndex(rowindex);
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(colindex);
                if (cell != null)
                {
                    myDataGridMain.ScrollIntoView(row, myDataGridMain.Columns[colindex]);
                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(colindex);
                    cell.Focus();
                    cell.Background = new SolidColorBrush(Colors.Red);
                }
            }
    
            public static T GetVisualChild<T>(Visual parent) where T : Visual
            {
                T childContent = default(T);
                int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < numVisuals; i++)
                {
                    Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                    childContent = v as T;
                    if (childContent == null)
                    {
                        childContent = GetVisualChild<T>(v);
                    }
                    if (childContent != null)
                    { break; }
                }
                return childContent;
            }

    如果以上两种方案都不能满足你的需求,请你详细的描述你的需求以供我更快的分析问题。

    谢谢

    Daisy Tian


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2020年10月22日 2:00