【发布时间】:2020-06-15 09:11:57
【问题描述】:
我将如何为代码中的特定控件创建一些资源?
此数据模板定义列表视图的列应如何呈现其内容。但是,由于此视图的特殊性质,我必须在代码中创建列以正确分配所需的属性。一切正常,唯一的例外是我没有找到将内容控件的内部数据模板分配给代码中内容控件的资源字典的正确方法(这是必需的,因为它会根据绑定的类型而变化,想象一下“...”中定义的其他模板)。我唯一缺少的部分是来自 xaml 的 <ContentControl.Resources> 的“翻译”。
<DataTemplate>
<ContentControl Content="{Binding}" Focusable="False">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type data:DataItem}">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding FirstProperty}"/>
<Label Content=" - "/>
<TextBox Text="{Binding SecondProperty}"/>
</StackPanel>
</DataTemplate>
...
</ContentControl.Resources>
</ContentControl>
</DataTemplate>
这是我目前的cs代码:
private DataTemplate GenerateSomeTemplate()
{
DataTemplate template = new DataTemplate(typeof(TextBlock));
FrameworkElementFactory contentElement = new FrameworkElementFactory(typeof(ContentControl));
template.VisualTree = contentElement;
contentElement.SetBinding(ContentControl.ContentProperty, new Binding() { }); // Might be wrong
contentElement.SetValue(ContentControl.FocusableProperty, false);
var displayTemplate = new DataTemplate(typeof(DataItem));
var layout = new FrameworkElementFactory(typeof(StackPanel));
var textBoxFirst = new FrameworkElementFactory(typeof(TextBox));
textBoxFirst.SetBinding(TextBox.TextProperty, new Binding() { Path = new PropertyPath("FirstProperty") });
layout.AppendChild(textBoxFirst);
var dashLabel = new FrameworkElementFactory(typeof(Label));
dashLabel.SetValue(Label.ContentProperty, " - ");
layout.AppendChild(dashLabel);
var textBoxSecond = new FrameworkElementFactory(typeof(TextBox));
textBoxFirst.SetBinding(TextBox.TextProperty, new Binding() { Path = new PropertyPath("SecondProperty") });
layout.AppendChild(textBoxSecond);
displayTemplate.VisualTree = layout;
// contentElement.AddResource(displayTemplate); // I need something like this...
return template;
}
【问题讨论】:
-
您是否考虑过使用 xamlreader.parse 并将此列定义构建为字符串?这是动态构建 UI 的推荐方法。它提供了一个显着的好处,即您可以在出现问题时抓住您的字符串并进行尝试。
标签: c# wpf resources controls datatemplate