WPF后台定义Datagrid的HeaderTemplate
需求
出于权限管理需要,不同权限的用户需要看到不同的界面,在我目前项目中,某datagrid的某一列在管理员可见界面中需要显示一个文本框,而其他权限的用户打开此界面则需隐藏该文本框,实现如下:
//DataGrid是要操作的datagrid的Name
DataGrid.Columns[4].HeaderTemplate = new DataTemplate() { VisualTree = CreateColHeader(userLevel) };
/// <summary>
/// 根据用户权限创建列头样式(只有管理员可见文本框,UserLevel是自定义的代表用户角色的枚举)
/// </summary>
/// <param name="userLevel"></param>
/// <returns></returns>
private FrameworkElementFactory CreateColHeader(UserLevel userLevel)
{
var stackPanelFactory = new FrameworkElementFactory(typeof(StackPanel));
var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
textBlockFactory.SetValue(TextBlock.TextProperty, "列名");
textBlockFactory.SetValue(TextElement.IsEnabledProperty, true);
stackPanelFactory.AppendChild(textBlockFactory);
if (userLevel == UserLevel.Admin)
{
var textBoxFactory = new FrameworkElementFactory(typeof(TextBox));
textBoxFactory.SetValue(TextBox.WidthProperty, (double)80);
textBoxFactory.SetValue(TextBox.HeightProperty, (double)20);
//为该文本框添加失去焦点事件
textBoxFactory.AddHandler(TextBox.LostFocusEvent, new RoutedEventHandler(BLKDLTB_LostFocus));
stackPanelFactory.AppendChild(textBoxFactory);
}
return stackPanelFactory;
}
private void BLKDLTB_LostFocus(object sender, RoutedEventArgs e)
{
//自定义失去焦点事件的代码
}