【问题标题】:Pass the bound object type to a converter?将绑定的对象类型传递给转换器?
【发布时间】:2021-03-17 10:24:35
【问题描述】:

我有一个在运行时更改其 ItemsSource 的 DataGrid。 我需要将当前对象类型传递给转换器。

基本上: // 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;}
   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 或 Bar 类型传递给我的 XAML 中的 datadrid 中的转换器: (我应该在这里放什么(而不是 ??????)不仅可以获取属性名称,还可以获取项目类型(Foo 或 Bar)?

<DataGrid.ColumnHeaderStyle>
    <Style TargetType="DataGridColumnHeader">
        <Setter Property="Content" Value="{Binding ConverterParameter=????, Converter={StaticResource PropertyDescriptionConverter}}" />
    </Style>
</DataGrid.ColumnHeaderStyle>

【问题讨论】:

  • Convert 方法中的value.GetType() 怎么样?
  • @Clemens,这就是我尝试过的,但是没有 ConverterParameter,转换器只会得到一个带有属性名称的 System.String。

标签: wpf data-binding datagrid


【解决方案1】:

经过几个小时的努力,只需使用一种变通方法即可使用 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;
    }
}

【讨论】:

    【解决方案2】:

    也许您可以为不同的类型使用模板选择器。

    此示例用于 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 2013-02-07
      • 2012-07-20
      • 2022-01-19
      相关资源
      最近更新 更多