简体   繁体   中英

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

Im new to 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

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

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

Here's a very basic example: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM