I am trying to have a context menu, in SL3 DataGrid Header similar to the one you guys have put up for GridView. Since DataGrid doesn't expose DataGridColumnHeader, I use the mouse enter event to espose the DataGridColumnHeader and initialize the Menu
But it doesn't have the desired behavior... the context menu appers very rarely... most times it doesn't appear at all. Can some one help me out
public class DataGridHeaderMenu |
{ |
private DataGrid grid = null; |
List<DataGridColumnHeader> headers = new List<DataGridColumnHeader>(); |
public DataGridHeaderMenu(DataGrid grid) |
{ |
this.grid = grid; |
} |
public static readonly DependencyProperty IsEnabledProperty |
= DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(DataGridHeaderMenu), |
new PropertyMetadata(new PropertyChangedCallback(OnIsEnabledPropertyChanged))); |
public static void SetIsEnabled(DependencyObject dependencyObject, bool enabled) |
{ |
dependencyObject.SetValue(IsEnabledProperty, enabled); |
} |
public static bool GetIsEnabled(DependencyObject dependencyObject) |
{ |
return (bool) dependencyObject.GetValue(IsEnabledProperty); |
} |
private static void OnIsEnabledPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) |
{ |
DataGrid grid = dependencyObject as DataGrid; |
if (grid != null) |
{ |
if ((bool) e.NewValue) |
{ |
// Create new GridViewHeaderMenu and attach RowLoaded event. |
DataGridHeaderMenu menu = new DataGridHeaderMenu(grid); |
menu.Attach(); |
} |
} |
} |
private void Attach() |
{ |
if (grid != null) |
{ |
this.grid.MouseEnter += new MouseEventHandler(grid_MouseEnter); |
} |
} |
void grid_MouseEnter(object sender, MouseEventArgs e) |
{ |
Point pt = e.GetPosition(this.grid); |
var list = VisualTreeHelper.FindElementsInHostCoordinates(pt, this.grid); |
foreach (UIElement elem in list) |
{ |
if (elem.GetType().Name == "DataGridColumnHeader") |
{ |
if (headers.Count == 0) |
{ |
headers.Add((DataGridColumnHeader)elem); |
InitializeMenus((DataGridColumnHeader)elem); |
} |
else |
{ |
if(!headers.Contains((DataGridColumnHeader)elem)) |
{ |
headers.Add((DataGridColumnHeader)elem); |
InitializeMenus((DataGridColumnHeader)elem); |
} |
} |
} |
} |
} |
//void grid_Loaded(object sender, RoutedEventArgs e) |
//{ |
// foreach (DataGridBoundColumn Column in this.grid.Columns) |
// { |
// if (Column != null) |
// { |
// InitializeMenus(Column); |
// } |
// } |
//} |
private void InitializeMenus(DataGridColumnHeader col) |
{ |
RadContextMenu contextMenu = new RadContextMenu(); |
RadMenuItem item = new RadMenuItem() { Header = String.Format(@"Sort Ascending by ""{0}""", col.Content.ToString()) }; |
contextMenu.Items.Add(item); |
contextMenu.EventName = "MouseRightButtonDown"; |
RadContextMenu.SetContextMenu(this.grid, contextMenu); |
} |
} |
But it doesn't have the desired behavior... the context menu appers very rarely... most times it doesn't appear at all. Can some one help me out