Wpf 是否将绑定对象类型传递给转换器?
我有一个DataGrid,它在运行时更改其ItemsSource。 我需要将当前对象类型传递给转换器 基本上: //dgDisplay-数据网格Wpf 是否将绑定对象类型传递给转换器?,wpf,data-binding,datagrid,Wpf,Data Binding,Datagrid,我有一个DataGrid,它在运行时更改其ItemsSource。 我需要将当前对象类型传递给转换器 基本上: //dgDisplay-数据网格 public class Foo { public string Id {get; set;} public string Data {get; set;} } // Property names are different public class Bar { public int Code {get; set;} publ
public class Foo
{
public string Id {get; set;}
public string Data {get; set;}
}
// Property names are different
public class Bar
{
public int Code {get; set;}
public string OtherData {get; set;}
}
// Later...
List<Foo> fooList = new List<Foo> { new Foo() { Id="ABC", Data = "data1" }}
List<Bar> barList = new List<Bar> { new Bar() { Code=3, OtherData = "data2" }}
if (condition)
this.dgDisplay.ItemsSource = fooList;
else
this.dgDisplay.ItemsSource = barList;
公共类Foo
{
公共字符串Id{get;set;}
公共字符串数据{get;set;}
}
//属性名称不同
公共类酒吧
{
公共整数代码{get;set;}
公共字符串OtherData{get;set;}
}
//后来。。。
List WOULIST=新列表{new Foo(){Id=“ABC”,Data=“data1”}
List barList=新列表{new Bar(){Code=3,OtherData=“data2”}
如果(条件)
this.dgddisplay.ItemsSource=傻瓜;
其他的
this.dgddisplay.ItemsSource=barList;
我想要的是将Foo或Bar类型传递给我的XAML中datadrid中的转换器:
(我应该在这里放置什么(而不是??)来不仅获取属性名称,还获取项目类型(Foo或Bar)
经过几个小时的努力,只需使用一个变通方法就可以使用AutoGeneratingColumn事件获得我想要的:
private void DgRefTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataGrid dg = (DataGrid)sender;
object src = dg.ItemsSource;
Type type = src.GetType().BaseType.GetGenericArguments()[0];
PropertyInfo property = type.GetProperty(e.Column.Header.ToString(), BindingFlags.Public | BindingFlags.Instance);
if (property.IsDefined(typeof(RTFieldAttribute), true))
{
e.Column.Header = ((RTFieldAttribute)property.GetCustomAttributes(typeof(RTFieldAttribute), true)[0]).HeaderText;
}
}
也许您可以为不同的类型使用模板选择器 这个例子是针对itemscontrol的,但我确信它也可以在这里使用
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type namespace:Foo}">
<Grid>
Create Template you want, bindings etc. for FOO
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type namespace:Bar}">
<Grid>
Create Template you want, bindings etc. for Bar
</Grid>
</DataTemplate>
</ItemsControl.Resources>
为FOO创建所需的模板、绑定等
创建所需的模板,为Bar创建绑定等
Convert方法中的value.GetType()
如何?@Clemens,这是我尝试过的,但是没有ConverterParameter,转换器只会得到一个带有属性名的System.String。
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type namespace:Foo}">
<Grid>
Create Template you want, bindings etc. for FOO
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type namespace:Bar}">
<Grid>
Create Template you want, bindings etc. for Bar
</Grid>
</DataTemplate>
</ItemsControl.Resources>