1、首先自定义控件——DataGridEx
添加依赖属性:DynamicBindHeadersCols
/// <summary>
/// DataGridEx.xaml 的交互逻辑
/// </summary>
public partial class DataGridEx : DataGrid
{
/// <summary>
/// 动态绑定DataGrid头和列
/// </summary>
public DataGrid DynamicBindHeadersCols
{
get { return (DataGrid)GetValue(DynamicBindHeadersColsProperty); }
set { SetValue(DynamicBindHeadersColsProperty, value); }
}
// Using a DependencyProperty as the backing store for dataGrid. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DynamicBindHeadersColsProperty =
DependencyProperty.Register("DynamicBindHeadersCols", typeof(DataGrid), typeof(DataGridEx), new PropertyMetadata((s, e) =>
{
var dp = s as DataGridEx;
foreach (var item in (e.NewValue as DataGrid).Columns)
{
dp.Columns.Add(new DataGridTextColumn()
{
Header = item.Header,
Binding = item.ClipboardContentBinding,
Width = item.Width,
Visibility = item.Visibility,
IsReadOnly = item.IsReadOnly,
});
}
}));
}
2、前台Xaml代码:
<Grid>
<controlex:DataGridEx ItemsSource="{Binding TestValues}" Style="{StaticResource DataGridExStyle}" DynamicBindHeadersCols="{Binding DataGrids}" />
</Grid>
3、ViewModel代码:
public class MainViewModel : INotify
{
public object TestValues { get; set; }
public MainViewModel()
{
DataGridLength length = new DataGridLength(1, DataGridLengthUnitType.Star);
dataGrids.Columns.Add(new DataGridTextColumn() { Header = "姓名", Binding = new Binding("Name"), Width = length, IsReadOnly = true });
dataGrids.Columns.Add(new DataGridTextColumn() { Header = "年龄", Binding = new Binding("Age"), Width = length, IsReadOnly = false });
TestValues = new[] {
new { Name = "张三", Age = 23 },
new { Name = "李四", Age = 24 },
new { Name = "王五", Age = 25 },
};
}
private DataGrid dataGrids = new DataGrid();
public DataGrid DataGrids
{
get { return dataGrids; }
set
{
dataGrids = value;
RaisePropertyChanged();
}
}
}
4、实现效果:
不到之处请大家多多指正,谢谢!