動的にDataGridの組み立て方法を紹介します。 一般の列を利用する場合 †this.dataGrid1.Columns.Add(new DataGridTextColumn { Header = "ID", Binding = new System.Windows.Data.Binding("id") }); テンプレート列(DataGridTemplateColumn)を利用する場合 †■方法一 テンプレートのXAMLのコードを定義する private string CreateColumnTemplate( string propertyName) { StringBuilder CellTemp = new StringBuilder(); CellTemp.Append("<DataTemplate "); CellTemp.Append("xmlns='http://schemas.microsoft.com/winfx/"); CellTemp.Append("2006/xaml/presentation' "); CellTemp.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>"); CellTemp.Append(String.Format("<TextBlock Text='{{Binding Path={0}}}'/>", propertyName)); CellTemp.Append("</DataTemplate>"); return CellTemp.ToString(); } C#側のソースコード: DataGridTemplateColumn dtc = new DataGridTemplateColumn(); dtc.CellTemplate = (DataTemplate)XamlReader.Load(CreateColumnTemplate( "id")); this.dataGrid2.Columns.Add(dtc); ■方法二 リソースにテンプレートを定義します。 <Application.Resources> <ResourceDictionary> <DataTemplate x:Key="myCellTemplate"> <TextBlock Text="{Binding Path=id}"/> </DataTemplate> </ResourceDictionary> </Application.Resources> C#側のソースコード: DataGridTemplateColumn dtc = new DataGridTemplateColumn(); dtc.CellTemplate = (DataTemplate)App.Current.Resources["myCellTemplate"]; this.dataGrid2.Columns.Add(dtc); ウィジェット型CM動画配信サービス manna [マナ] コメント: |