我希望能够根据我的数据源以编程方式创建 DataGridTemplateColumns。例如,如果我的源在特定列中有一个日期,我希望能够利用 Datepicker 控件。我知道这可以在设计时使用 xaml 和 DataGridTemplateColumn 轻松完成,但是,我将如何在运行时完成此任务?
我的最佳选择是 xamlreader.load 还是更传统的路线,例如:
Dim TempCol As Microsoft.Windows.Controls.DataGridTemplateColumn
我在后者方面没有取得任何成功。
Thanks.
-Paul
编辑:
这是我尝试使用的代码:
Dim TempCol As New Microsoft.Windows.Controls.DataGridTemplateColumn
TempCol.CellEditingTemplate = DataTemplate.Equals(DatePicker)
我收到 DatePicker 是一种类型,不能用作表达式。
我将此基于 WPF Toolkit 演示。http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-datagrid-feature-walkthrough.aspx http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-datagrid-feature-walkthrough.aspx
<dg:DataGridTemplateColumn Header="Date" MinWidth="100">
<dg:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<dg:DatePicker SelectedDate="{Binding Date}" SelectedDateFormat="Short" />
</DataTemplate>
</dg:DataGridTemplateColumn.CellEditingTemplate>
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Date, StringFormat=d}" />
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
Thanks!
您的代码不起作用的原因是您正在设置CellEditingTemplate
列到一个bool
(调用的结果DataTemplate.Equals()
,而不是在代码中创建模板的实例。
您可以使用类似以下内容在代码中创建模板(相当于您提供的 XAML 代码片段):
DataGridTemplateColumn col = new DataGridTemplateColumn();
col.Header = "Date";
// Create a factory. This will create the controls in each cell of this
// column as needed.
FrameworkElementFactory factory =
new FrameworkElementFactory(typeof(DatePicker));
// Bind the value of this cell to the value of the Date property of the
// DataContext of this row. The StringFormat "d" will be used to display
// the value.
Binding b = new Binding("Date");
b.StringFormat = "d";
factory.SetValue(DatePicker.SelectedDateProperty, b);
// Create the template itself, and add the factory to it.
DataTemplate cellEditingTemplate = new DataTemplate();
cellEditingTemplate.VisualTree = factory;
col.CellEditingTemplate = cellEditingTemplate;
我不确定这种方法是否比您自己加载 XAML 更有效。也许尝试两种方法,看看哪一种最适合您,并且效果更快?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)