36

クエリの結果を WPF データグリッドに表示しようとしています。私がバインドしている ItemsSource タイプはIEnumerable<dynamic>. 返されるフィールドは実行時まで決定されないため、クエリが評価されるまでデータの型はわかりません。各「行」はExpandoObject、フィールドを表す動的プロパティを持つ として返されます。

AutoGenerateColumns(以下のように)静的型の場合と同じように列を生成できることを願ってExpandoObjectいましたが、そうではないようです。

<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Results}"/>

これを宣言的に行う方法はありますか、それとも C# で命令的にフックする必要がありますか?

編集

これで正しい列が得られます:

// ExpandoObject implements IDictionary<string,object> 
IEnumerable<IDictionary<string, object>> rows = dataGrid1.ItemsSource.OfType<IDictionary<string, object>>();
IEnumerable<string> columns = rows.SelectMany(d => d.Keys).Distinct(StringComparer.OrdinalIgnoreCase);
foreach (string s in columns)
    dataGrid1.Columns.Add(new DataGridTextColumn { Header = s });

したがって、列を IDictionary 値にバインドする方法を理解する必要があります。

4

4 に答える 4

30

最終的に、次の 2 つのことを行う必要がありました。

  1. クエリによって返されたプロパティのリストから列を手動で生成します
  2. DataBinding オブジェクトを設定する

その後、組み込みのデータバインディングが開始され、正常に機能し、プロパティ値をExpandoObject.

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Results}" />

// Since there is no guarantee that all the ExpandoObjects have the 
// same set of properties, get the complete list of distinct property names
// - this represents the list of columns
var rows = dataGrid1.ItemsSource.OfType<IDictionary<string, object>>();
var columns = rows.SelectMany(d => d.Keys).Distinct(StringComparer.OrdinalIgnoreCase);

foreach (string text in columns)
{
    // now set up a column and binding for each property
    var column = new DataGridTextColumn 
    {
        Header = text,
        Binding = new Binding(text)
    };

    dataGrid1.Columns.Add(column);
}
于 2010-01-02T04:46:58.273 に答える
6

ここでの問題は、clr が ExpandoObject 自体の列を作成することですが、ExpandoObject のグループが互いに同じプロパティを共有するという保証はなく、どの列を作成する必要があるかをエンジンが知るための規則はありません。

おそらく、Linq 匿名型のようなものがうまく機能するでしょう。使用しているデータグリッドの種類はわかりませんが、バインディングはすべて同じである必要があります。これは、テレリック データグリッドの簡単な例です。
テレリック フォーラムへのリンク

これは実際には真に動的ではなく、コンパイル時に型を認識する必要がありますが、これは実行時にこのような設定を行う簡単な方法です。

どのような種類のフィールドを表示するのか本当にわからない場合、問題はもう少し複雑になります。考えられる解決策は次のとおりです。

動的 linq を使用すると、実行時に文字列を使用して匿名型を作成できます。これは、クエリの結果から組み立てることができます。2 番目のリンクの使用例:

var orders = db.Orders.Where("OrderDate > @0", DateTime.Now.AddDays(-30)).Select("new(OrderID, OrderDate)");

いずれにせよ、基本的な考え方は、リフレクションによって共有パブリック プロパティを見つけることができるオブジェクトのコレクションに itemgrid を何らかの方法で設定することです。

于 2009-12-31T18:36:20.667 に答える
4

Xaml の動的列バインディングからの私の回答

この疑似コードのパターンに従うアプローチを使用しました

columns = New DynamicTypeColumnList()
columns.Add(New DynamicTypeColumn("Name", GetType(String)))
dynamicType = DynamicTypeHelper.GetDynamicType(columns)

DynamicTypeHelper.GetDynamicType() は、単純なプロパティを持つ型を生成します。このようなタイプを生成する方法の詳細については、この投稿を参照してください

次に、実際に型を使用するには、次のようにします

Dim rows as List(Of DynamicItem)
Dim row As DynamicItem = CType(Activator.CreateInstance(dynamicType), DynamicItem)
row("Name") = "Foo"
rows.Add(row)
dataGrid.DataContext = rows
于 2009-12-31T19:08:37.027 に答える
2

OPによって受け入れられた回答がありますがAutoGenerateColumns="False"、元の質問が求めていたものとはまったく異なります。幸いなことに、自動生成された列でも解決できます。ソリューションの鍵は、DynamicObject静的プロパティと動的プロパティの両方を持つことができる です。

public class MyObject : DynamicObject, ICustomTypeDescriptor {
  // The object can have "normal", usual properties if you need them:
  public string Property1 { get; set; }
  public int Property2 { get; set; }

  public MyObject() {
  }

  public override IEnumerable<string> GetDynamicMemberNames() {
    // in addition to the "normal" properties above,
    // the object can have some dynamically generated properties
    // whose list we return here:
    return list_of_dynamic_property_names;
  }

  public override bool TryGetMember(GetMemberBinder binder, out object result) {
    // for each dynamic property, we need to look up the actual value when asked:
    if (<binder.Name is a correct name for your dynamic property>) {
      result = <whatever data binder.Name means>
      return true;
    }
    else {
      result = null;
      return false;
    }
  }

  public override bool TrySetMember(SetMemberBinder binder, object value) {
    // for each dynamic property, we need to store the actual value when asked:
    if (<binder.Name is a correct name for your dynamic property>) {
      <whatever storage binder.Name means> = value;
      return true;
    }
    else
      return false;
  }

  public PropertyDescriptorCollection GetProperties() {
    // This is where we assemble *all* properties:
    var collection = new List<PropertyDescriptor>();
    // here, we list all "standard" properties first:
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this, true))
      collection.Add(property);
    // and dynamic ones second:
    foreach (string name in GetDynamicMemberNames())
      collection.Add(new CustomPropertyDescriptor(name, typeof(property_type), typeof(MyObject)));
    return new PropertyDescriptorCollection(collection.ToArray());
  }

  public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => TypeDescriptor.GetProperties(this, attributes, true);
  public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
  public string GetClassName() => TypeDescriptor.GetClassName(this, true);
  public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
  public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
  public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
  public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
  public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
  public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
  public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
  public object GetPropertyOwner(PropertyDescriptor pd) => this;
}

ICustomTypeDescriptor実装では、ほとんどの場合、簡単な方法で の静的関数を使用できますTypeDescriptorGetProperties()実際の実装が必要なものです: 既存のプロパティを読み取り、動的なものを追加します。

抽象的であるためPropertyDescriptor、継承する必要があります。

public class CustomPropertyDescriptor : PropertyDescriptor {
  private Type componentType;

  public CustomPropertyDescriptor(string propertyName, Type componentType)
    : base(propertyName, new Attribute[] { }) {
    this.componentType = componentType;
  }

  public CustomPropertyDescriptor(string propertyName, Type componentType, Attribute[] attrs)
    : base(propertyName, attrs) {
    this.componentType = componentType;
  }

  public override bool IsReadOnly => false;

  public override Type ComponentType => componentType;
  public override Type PropertyType => typeof(property_type);

  public override bool CanResetValue(object component) => true;
  public override void ResetValue(object component) => SetValue(component, null);

  public override bool ShouldSerializeValue(object component) => true;

  public override object GetValue(object component) {
    return ...;
  }

  public override void SetValue(object component, object value) {
    ...
  }
于 2016-02-08T15:54:31.070 に答える