まず、ListView
自分では何もしません。ListView.View
のインスタンスに設定する必要がありますGridView
。
最近、動的列の問題を解決する必要がありました。私が選んだソリューションは、バインド可能で MVVM と互換性があります。ソース構造の更新時に列を動的に挿入および削除する動作を (GridView の拡張を避けるために)作成しました。この動作には、列を定義するクラスのインスタンスにバインドする依存関係プロパティが必要です。列クラスでは、列がソース データのバインド先のプロパティである列と、キー (セルの種類を表す) を定義できる必要があります。
public class ColumnDefinition
{
public string Key{ get; set}
public string ContentBindingPath { get; set;}
}
列の構造が変更されると、ビヘイビアーによって列が構築され、アタッチされた GridView に挿入 (または削除) されます。動作は、動作で定義された一連のキーと値のペアに基づいて各列を構築します。これは、XAML がセル テンプレートを指定して新しい列に適用できるようにし、関心の分離を強制するためです。
public class CellTemplateDefinition
{
public string Key { get; set; }
public DataTemplate ColumnTemplate { get; set;}
}
public class DynamicColumnBehavior: Behavior<GridView>
{
public IEnumerable<ColumnDefinition> Columns
{
get { return (IEnumerable<ColumnDefinition>)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
// Using a DependencyProperty as the backing store for Columns. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ColumnsProperty = DependencyProperty.Register("Columns", typeof(IEnumerable<ColumnDefinition>), typeof(DynamicColumnBehavior), new UIPropertyMetadata(null));
public static void OnColumnsChanged(DependencyObject sender, DependencyPropertyChangedEventArgsargs)
{
DynamicColumnBehavior behavior = sender as DynamicColumnBehavior;
if(behavior != null) behavior.UpdateColumns();
}
public IEnumerable<CellTemplateDefinition> Cells { get; set; }
private void UpdateColumns(){ throw new NotImplementedException("I left this bit for you to do ;)");}
}