データグリッドへのプロパティとしてのサブオブジェクトを持つオブジェクトのバインド
-
03-07-2019 - |
質問
サブオブジェクトを持つオブジェクトを使用しています(下の例を参照)。 List<rootClass>
をデータグリッドにバインドしようとしています。 List<>
を含むセルでsubObject
をバインドすると、次の値... "namespace.subObject" ...
が表示され、文字列値が正しく表示されます。
理想的には<!>#8220; Description <!>#8221;データセル内のsubObject.Description
のプロパティ。 <=>をマップしてデータセルに表示するにはどうすればよいですか?
public class subObject
{
int id;
string description;
public string Description
{ get { return description; } }
}
public class rootClass
{
string value1;
subObject value2;
string value3;
public string Value1
{ get { return value1; } }
public subObject Value2
{ get { return value2; } }
public string Value3
{ get { return value3; } }
}
解決
間違えなければ、subObjectで.ToString()を呼び出した結果が表示されるため、これをオーバーライドしてDescriptionの内容を返すことができます。
Value1.Descriptionへのバインドだけを試みましたか? (私はそれが機能しないと推測しています)。
バインド時にListの代わりに使用できるクラスがあり、これを処理し、ITypedListを実装します。これにより、コレクションがより多くの<!> quot; properties <!> quot;を提供できます。計算されたプロパティを含むオブジェクト用。
現在持っているファイルの最新バージョンは次のとおりです。
https://gist.github.com/lassevk/64ecea836116882a5d59b0f235858044
使用するには:
List<rootClass> yourList = ...
TypedListWrapper<rootClass> bindableList = new TypedListWrapper<rootClass>(yourList);
bindableList.BindableProperties = "Value1;Value2.Description;Value3.Description";
gridView1.DataSource = bindableList;
基本的に、TypedList<T>
ではなくList<T>
のインスタンスにバインドし、BindablePropertiesプロパティを調整します。作業中にいくつかの変更があります。たとえば、BindablePropertiesを自動的に作成するだけで、まだトランクにはありません。
次のような計算プロパティを追加することもできます。
yourList.AddCalculatedProperty<Int32>("DescriptionLength",
delegate(rootClass rc)
{
return rc.Value2.Description.Length;
});
または.NET 3.5の場合:
yourList.AddCalculatedProperty<Int32>("DescriptionLength",
rc => rc.Value2.Description.Length);
他のヒント
DataGridViewColumn
(タグ)に言及しているので、winformsを意味すると仮定します。
サブプロパティへのアクセスは苦痛です。通貨マネージャーはリストにバインドされているため、デフォルトでは即時プロパティにのみアクセスできます。ただし、カスタムタイプ記述子を使用することで、絶対に必要な場合は これを回避できます。 <!> quot; Foo_Bar <!> quot;など、別のトークンも使用する必要があります。 <!> quot; Foo.Bar <!> quot;の代わりに。ただし、これはPropertyDescriptor
、ICustomTypeDescriptor
、おそらくTypeDescriptionProvider
の知識を必要とするメジャーの作業量であり、ほぼ間違いなく価値がありません
最も簡単な修正方法は、プロパティをシム/パススルーとして公開することです:
public string Value2Description {
get {return Value2.Description;} // maybe a null check too
}
次に<!> quot; Value2Description <!> quot;にバインドします。など。
ASP.NETを使用しているかどうかはわかりませんが、使用している場合は、テンプレート列とEval()メソッドを使用して、ネストされたオブジェクトの値を表示できます。例えば。 subObjectのDescriptionプロパティを表示するには:
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal Text='<%# Eval("Value2.Description") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
あなたが望んでいるのはこのようなものかどうかわからない...
次のようなメソッドを書くことができます:
protected string getSubObject(object o)
{
string result = string.empty;
try
{
result = ((subObject)o).Description;
}
catch
{ /*Do something here to handle/log your exception*/ }
return result;
}
次に、オブジェクトを次のようにバインドします:
<asp:Literal Text='<%# getSubObject(Eval("Value2")) %>' runat="server" />