Wpf 在运行时更改DataTemplate TextBlock属性
我有一个DataTemplate,定义如下: 我在运行时使用以下代码访问它:Wpf 在运行时更改DataTemplate TextBlock属性,wpf,datatemplate,Wpf,Datatemplate,我有一个DataTemplate,定义如下: 我在运行时使用以下代码访问它: else { template = (DataTemplate)FindResource("GridViewTextBlockDataTemplate"); var textblock = (TextBlock) template.LoadContent();
else
{
template = (DataTemplate)FindResource("GridViewTextBlockDataTemplate");
var textblock = (TextBlock) template.LoadContent();
textblock.Text = "bye";
//textblock.SetBinding(TextBlock.TextProperty, new Binding("[" + current.Key + "]"));
}
var column = new GridViewColumn
{
Header = current.Key,
CellTemplate = template
};
gridView.Columns.Add(column);
}
现在我想把textblock属性改成我该怎么做?它总是显示为空。数据模板是用于创建内容的模板。在模板上调用LoadContent时,它将创建该模板定义的内容。因此,当您更改TextBlock时,它只应用于内容的一个实例,而不应用于DataTemplate本身 我假设您需要这样做才能基于传递给函数的属性生成绑定。可以通过直接在代码中生成模板来实现这一点。它比XAML更难理解,但这应该可以做到:
private DataTemplate GenerateTextBlockTemplate(string property)
{
FrameworkElementFactory factory = new FrameworkElementFactory(typeof(TextBlock));
factory.SetBinding(TextBlock.TextProperty, new Binding(property));
return new DataTemplate { VisualTree = factory };
}
谢谢我使用的是FrameworkElementFactory,但是我需要访问一些属性,比如TreeView.Items属性,这些属性不能作为依赖项属性使用。FrameworkElementFactory是XAML解析器创建数据模板的方式。。。因此,如果您可以在XAML中完成,那么您可以在代码中完成。你到底需要做什么才能让这不适合你?