我有一个用XAML编写的WPF DataGrid
,我正在转换为C#(不要问)。
它看起来像这样(为简洁起见省略了一些属性):
var Card = new DataGrid() {
Background = Brushes.LightYellow,
BorderBrush = Brushes.DimGray,
ColumnWidth = new DataGridLength(100),
Columns = {
new DataGridTextColumn() {
Binding = new Binding("In"),
Header = "In"
},
new DataGridTextColumn() {
Binding = new Binding("Out"),
Header = "Out"
},
new DataGridTextColumn() {
Binding = new Binding("Hours"),
Header = "Hours"
}
},
RowHeaderTemplate = new DataTemplate(typeof(DataGridRowHeader)) {
VisualTree = Days
},
RowHeaderWidth = 115,
RowHeight = 50
};
Days
设置如下:
var Days = new FrameworkElementFactory(typeof(TextBlock));
Days.SetBinding(TextBlock.TextProperty, new Binding("Day"));
Days.SetValue(TextBlock.BackgroundProperty, Brushes.Lime);
运行时,DataGrid
的{{1}}为空白(RowHeader
,而不是LightYellow
)。
我也试过了Lime
,但没有用。
我哪里错了?如何以编程方式设置Card.RowHeaderTemplate.VisualTree = Days;
?
答案 0 :(得分:1)
应使用XAML加载创建模板。使用元素工厂已过时且不再受支持(在某些情况下可能有效,但在其他情况下无效)。
例如,Caliburn.Micro creates default data templates就像这样:
public static DataTemplate DefaultHeaderTemplate = (DataTemplate)
#if SILVERLIGHT || WinRT
XamlReader.Load(
#else
XamlReader.Parse(
#endif
"<DataTemplate " +
" xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>" +
" <TextBlock Text=\"{Binding DisplayName, Mode=TwoWay}\" />" +
"</DataTemplate>"
);
您可能会觉得有用的另一个链接:Creating WPF Data Templates in Code The Right Way。它包括使用XML和XAML类创建XAML字符串的示例,以及对程序集和内容的引用。