WPF Datagrid:如何以编程方式更改单个单元格的边框粗细?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14908196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:33:57  来源:igfitidea点击:

WPF Datagrid: How to change border thickness of a single cell programatically?

c#wpfwpfdatagrid

提问by nfinium

Im new to WPF

我是 WPF 的新手

Im trying to change the border of a single cell depending on the column and row index. So far I already have the code for getting the column and row index.

我试图根据列和行索引更改单个单元格的边框。到目前为止,我已经有了获取列和行索引的代码。

Now I need to get 'that cell' and change its border..

现在我需要得到“那个单元格”并改变它的边框..

This is my Code , but its not working:

这是我的代码,但它不起作用:

I got this method from net:

我从网上得到了这个方法:

    public static 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;
    }

Then this where I need to change the cell properties..

然后这是我需要更改单元格属性的地方..

           int rows = 0;
            int col = 0;
        while (col < myDG.Columns.Count)
        {
            rows = 0;
            while (rows < myDG.Items.Count)
            {
                DataGridRow row = (DataGridRow)myDG.ItemContainerGenerator.ContainerFromIndex(rows);

                if (row != null)
                {

                    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
                    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(col);

                    cell.BorderThickness = new Thickness (2,2,2,2);
                    cell.BorderBrush= Brushes.Black;


                rows++;
            }
            col++;
        }

Any Idea? Thanks in Advance

任何的想法?提前致谢

回答by JMan

Try to avoid code behind in your WPF application. Prefer to set the thickness property to a binding property on your datacontext.

尽量避免在 WPF 应用程序中隐藏代码。最好将厚度属性设置为数据上下文上的绑定属性。

then you can convert this value to a valid value for that property by setting a valueconverter.

然后您可以通过设置 valueconverter 将此值转换为该属性的有效值。

Here's a very basic example: http://wpftutorial.net/DataBindingOverview.html

这是一个非常基本的示例:http: //wpftutorial.net/DataBindingOverview.html

So if you're new to WPF try searching some video's about MVVM.
Laurent Bignon has made a few excellent ones to explain the whole concept

因此,如果您不熟悉 WPF,请尝试搜索一些有关 MVVM 的视频。
Laurent Bignon 做了一些很好的解释整个概念