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 ][ ]
[开发者_如何学Go ][ highlighted ][ ]
Is there an easy way to do this? Thanks!
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.
精彩评论