WPF DataGrid の列の動的バインディング
WPF DataGrid の Columns プロパティは読み取り専用であるため、可変数の列を使用してデータをプログラムでバインドしようとすると問題が発生します。
次のシナリオを考えてみましょう:
<code class="language-csharp">class Data { public IList<ColumnDescription> ColumnDescriptions { get; set; } public string[][] Rows { get; set; } }</code>
このデータを DataGrid に表示するには、列を動的に生成する必要があります:
<code class="language-csharp">for (int i = 0; i < data.ColumnDescriptions.Count; i++) { dataGrid.Columns.Add(new DataGridTextColumn { Header = data.ColumnDescriptions[i].Name, Binding = new Binding(string.Format("[{0}]", i)) }); }</code>
このコードを XAML ファイルのデータ バインディングに置き換えることはできますか?
解決策: BindableColumns に属性を添付する
Columns プロパティはまだ読み取り専用ですが、BindableColumns という追加のプロパティを作成できます。
<code class="language-csharp">public class DataGridColumnsBehavior { public static readonly DependencyProperty BindableColumnsProperty = DependencyProperty.RegisterAttached("BindableColumns", typeof(ObservableCollection<DataGridTextColumn>), typeof(DataGridColumnsBehavior), new UIPropertyMetadata(null, BindableColumnsPropertyChanged)); // ... }</code>
その後、XAML で BindableColumns プロパティを DataGridColumn オブジェクトの ObservableCollection にバインドできます。
<code class="language-xml"><DataGrid Name="dataGrid"> local:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection}" AutoGenerateColumns="False" ... /></code>
使用方法
BindableColumns 動作を使用するには、DataGridColumn オブジェクトの ObservableCollection を定義します。
<code class="language-csharp">public ObservableCollection<DataGridTextColumn> ColumnCollection { get; private set; }</code>
CollectionChanged イベントを介して列を動的に更新します:
<code class="language-csharp">columns.CollectionChanged += (sender, e2) => { // ... };</code>
この回避策により、読み取り専用の Columns プロパティを変更せずに、DataGrid 内の列のデータ バインディングが可能になります。
以上がXAML を使用して列を WPF DataGrid に動的にバインドする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。