我的viewModel中有DataTable
属性:
public class MainViewModel()
{
public MainViewModel()
{ PopulateDataTable(); }
private DataTable employeeDataTable;
public DataTable EmployeeDataTable
{
get { return employeeDataTable; }
set
{
employeeDataTable = value;
OnPropertyChanged("EmployeeDataTable");
}
}
private void PopulateDataTable()
{
var _ds = new DataSet("Test");
employeeDataTable = new DataTable();
employeeDataTable = _ds.Tables.Add("DT");
for (int i = 0; i < 20; i++)
{
employeeDataTable.Columns.Add(i.ToString());
}
for (int i = 0; i < 20; i++)
{
var theRow = employeeDataTable.NewRow();
for (int j = 0; j < 20; j++)
{
if (j % 2 == 0)
{
theRow[j] = 1;
}
else
theRow[j] = false;
}
employeeDataTable.Rows.Add(theRow);
}
}
}
我在XAML中创建了DataTemplates
:
<Window.Resources>
<DataTemplate x:Key="IntTemplate">
<StackPanel>
<Label Content="Integer"/>
<TextBlock Text="{Binding Path=WhatShouldIWriteHere?}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="BooleanTemplate">
<StackPanel>
<Label Content="Boolean"/>
<CheckBox IsEnabled="{Binding Path=WhatShouldIWriteHere?}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
Window的代码隐藏使用必要的DataTemplate:
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataTemplate dt = null;
switch (e.PropertyType.ToString())
{
case "System.Int32":
dt = (DataTemplate)Resources["IntegerTemplate"];
break;
case "System.Boolean":
dt = (DataTemplate)Resources["BooleanTemplate"];
break;
}
if (dt != null)
{
DataGridTemplateColumn c = new DataGridTemplateColumn()
{
CellTemplate = dt,
Header = e.Column.Header,
HeaderTemplate = e.Column.HeaderTemplate,
HeaderStringFormat = e.Column.HeaderStringFormat,
SortMemberPath = e.PropertyName
};
e.Column = c;
}
}
我的问题是我应该在DataTemplates的控件(TextBlock
和CheckBox
)的绑定中写什么?
<DataTemplate x:Key="IntTemplate">
<StackPanel>
<Label Content="Integer"/>
<TextBlock Text="{Binding Path=WhatShouldIWriteHere?}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="BooleanTemplate">
<StackPanel>
<Label Content="Boolean"/>
<CheckBox IsEnabled="{Binding Path=WhatShouldIWriteHere?}"/>
</StackPanel>
</DataTemplate>
答案 0 :(得分:0)
.NET 4.X和仅限上限的解决方案
查看DLR DynamicObject data type,您可以定义从动态继承的自有类型并绑定到该类型的属性,然后覆盖TryGetMembers解析请求的数据
您的类型应该使用(通过聚合)该DataTable实例