我遇到一个问题,我在运行时获取类的类型,我使用System.Reflection.Emit
向其添加了一个布尔属性,现在我需要将DataGridTemplateColumn(Takes Checkboxes)绑定到我的属性,我我尝试了许多解决方案并失败了,这是我的示例代码。
ColumnDynamicBuilder.cs:
public ColumnDynamicBuilder(Type typeOfClass)
{
myAsmName.Name = "MyDynamicAssembly";
// To generate a persistable assembly, specify AssemblyBuilderAccess.RunAndSave.
AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(myAsmName,
AssemblyBuilderAccess.RunAndSave);
// Generate a persistable single-module assembly.
ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule(myAsmName.Name, myAsmName.Name + ".dll");
myTypeBuilder = myModBuilder.DefineType("CheckColumn", TypeAttributes.Public);
myTypeBuilder.SetParent(typeOfClass);
PropertyBuilder custNamePropBldr = myTypeBuilder.DefineProperty("CheckBoxColumn", PropertyAttributes.HasDefault, typeof(bool), null);
// The property set and property get methods require a special set of attributes.
MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
// Define the "get" accessor method for CustomerName.
MethodBuilder custNameGetPropMthdBldr = myTypeBuilder.DefineMethod("get_CheckColumn", getSetAttr, typeof(bool), Type.EmptyTypes);
ILGenerator custNameGetIL = custNameGetPropMthdBldr.GetILGenerator();
custNameGetIL.Emit(OpCodes.Ret);
// Define the "set" accessor method for CustomerName.
MethodBuilder custNameSetPropMthdBldr = myTypeBuilder.DefineMethod("set_CheckColumn", getSetAttr, typeof(bool), new Type[] { typeof(bool)});
ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();
custNameSetIL.Emit(OpCodes.Ret);
// Last, we must map the two methods created above to our PropertyBuilder to their corresponding behaviors, "get" and "set" respectively.
custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);
myTypeBuilder.CreateType();
// Save the assembly so it can be examined with Ildasm.exe, or referenced by a test program.
myAsmBuilder.Save(myAsmName.Name + ".dll");
properties = myTypeBuilder.GetProperties();
}
在这一部分中,我创建了一个名为CheckBoxColumn
的属性,并将其与在myTypeBuilder
中找到的静态属性一起添加到typeOfClass
。
然后我写了一个WPF示例供CheckBox绑定,这是示例代码。
ColumnDynamicBuilder.Xaml:
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<CheckBox Content=" Select All"x:Name="cb_HeaderCheckBox" Checked="cb_HeaderCheckBox_Checked" Unchecked="cb_HeaderCheckBox_Unchecked" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Border Background="Transparent" Padding="6 0 6 0" HorizontalAlignment="Center">
<CheckBox x:Name="cb_CheckBoxColumn" Click="cb_CheckBoxColumn_Click" IsChecked ="{Binding CheckBoxColumn, Mode=TwoWay, UpdateSourceTrigger=Explicit}" />
</Border>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
预先感谢您的帮助。