wpf 中给DataGrid控件增加边框
进来做一个打印功能。需要展示,客户的车牌号,物料名称,毛重,净重,单个文本框是可以带有边框的。但是不好对齐。
整体的布局采用DataGrid来试下。
但是 DataGrid本身的ShowLine样式为虚线,切不美观。
所以需要自定义。
这里用到 wpf 中的附加属性。 RegisterAttached
下面代码展示 wpf DataGrid中使用附加属性增加边框。
···
public class GridLineHelper
{
public static bool GetShowBorder(DependencyObject obj)
{
return (bool)obj.GetValue(ShowBorderProperty);
}
public static void SetShowBorder(DependencyObject obj, bool value)
{
obj.SetValue(ShowBorderProperty, value);
}
public static readonly DependencyProperty ShowBorderProperty =
DependencyProperty.RegisterAttached("ShowBorder", typeof(bool), typeof(GridLineHelper), new PropertyMetadata(OnShowBorderChanged));
//事件处理,需要手工编写,必须是静态方法
private static void OnShowBorderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var grid = d as Grid;
string name = grid.Name;
if ((bool)e.OldValue)
{
grid.Loaded -= (s, arg) => { };
}
if ((bool)e.NewValue)
{
grid.Loaded += (s, arg) =>
{
//根据Grid中子控件的个数去添加边框,同时考虑合并的情况
var controls = grid.Children;
var count = controls.Count;
for (int i = 0; i < count; i++)
{
var item = controls[i] as FrameworkElement;
var border = new Border()
{
BorderBrush = new SolidColorBrush(Colors.LightGray),
BorderThickness = new Thickness(1)
};
var row = Grid.GetRow(item);
var column = Grid.GetColumn(item);
var rowspan = Grid.GetRowSpan(item);
var columnspan = Grid.GetColumnSpan(item);
Grid.SetRow(border, row);
Grid.SetColumn(border, column);
Grid.SetRowSpan(border, rowspan);
Grid.SetColumnSpan(border, columnspan);
grid.Children.Add(border);
}
};
}
}
}
···
增加以上方法后。在xaml中使用附加属性就能够正确显示 边框了。
很赞哦! (0)