Silverlight Datagrid: Highlight an entire Column?

天大地大妈咪最大 提交于 2019-12-25 04:49:06

问题


I have a DataGrid in my Silverlight application, and would like to "highlight" an entire column when any cell in that column is selected.

E.g., given this grid (where "[ ]" represents a cell):

[     ][     ][     ]
[     ][     ][     ]
[     ][     ][     ]

If I select a cell, like this

[     ][ selected ][     ]
[     ][          ][     ]
[     ][          ][     ]

I would like all the cells in that column, including the selected cell, to be "highlighted" (can be as simple as just changing the background color):

[     ][  selected   ][     ]
[     ][ highlighted ][     ]
[     ][ highlighted ][     ]

Is there an easy way to do this? Thanks!


回答1:


Here is the start of behavior that should point you in the right direction

    public class DataGridHighlightBehavior : Behavior<DataGrid>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.CurrentCellChanged += AssociatedObject_CurrentCellChanged;
    }

    void AssociatedObject_CurrentCellChanged(object sender, EventArgs e)
    {
        foreach (object i in AssociatedObject.ItemsSource)
        {
            var item = AssociatedObject.CurrentColumn.GetCellContent(i);
            if (item == null)
                return;
            var parent = GetParent<DataGridCell>(item);
            if (parent != null)
                parent.Background = new SolidColorBrush(Colors.Red);
        }
    }

    public static T GetParent<T>(DependencyObject source)
            where T : DependencyObject
    {
        DependencyObject parent = VisualTreeHelper.GetParent(source);
        while (parent != null && !typeof(T).IsAssignableFrom(parent.GetType()))
        {
            parent = VisualTreeHelper.GetParent(parent);
        }
        return (T)parent;
    }
}

You will need to add code to change the old cells back to their normal state. My initial thought was to modify their current visual state so they show selected, but couldn't remember how (if you can) to do that from outside the class.



来源:https://stackoverflow.com/questions/2829846/silverlight-datagrid-highlight-an-entire-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!