Wpf 未找到资源,但已找到

Wpf 未找到资源,但已找到,wpf,resourcedictionary,Wpf,Resourcedictionary,我使用以下部分代码向DataGridTemplateColumn添加textblock: FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock)); tb.SetValue(TextBlock.IsHitTestVisibleProperty, false); tb.SetBinding(TextBlock.DataContextProperty, new Binding("doorparameters

我使用以下部分代码向DataGridTemplateColumn添加textblock:

FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
tb.SetValue(TextBlock.IsHitTestVisibleProperty, false);
tb.SetBinding(TextBlock.DataContextProperty, new Binding("doorparameters[" + pid.ToString() + "]"));
tb.SetResourceReference(TextBlock.StyleProperty, "ParameterTextBlockStyle");
一切正常,但当我在调试模式下运行时,输出窗口显示以下错误:

System.Windows.ResourceDictionary警告:9:未找到资源;ResourceKey='ParameterTextBlockStyle'

“ParameterTextBlockStyle”是在datagrid的资源中定义的,而不是在窗口资源中定义的。奇怪的是,不管在哪种资源中定义样式,我总是得到这样的信息

可以忽略此错误吗?

试试这个

FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
tb.SetValue(TextBlock.IsHitTestVisibleProperty, false);
tb.SetBinding(TextBlock.DataContextProperty, new Binding("doorparameters[" + pid.ToString() + "]"));
tb.SetResourceReference(TextBlock.StyleProperty, (Style)dataGrid.FindResource("ParameterTextBlockStyle"));

SetResourceReference
相当于
DynamicResource
,而IIRC
DataGridTemplateColumn
使用了一些技巧来呈现自己。(对不起,现在我想不起来确切是什么了)

您可以尝试等效的
StaticResource
,这应该更可靠,因为它不必通过遍历逻辑树来找到样式:

tb.SetValue(FrameworkElement.StylePropertyProperty,
            dataGrid.FindResource("ParameterTextBlockStyle"));

tb是类FrameworkElementFactory,它不直接公开Style属性。@抱歉,当然,我没有注意到。我已更新我的答案。错误现在为:“System.Windows.ResourceDictionary警告:9:未找到资源;ResourceKey='System.Windows.Style';ResourceKey.HashCode='20';ResourceKey.Type='System.Windows.Style''您能试试吗,
Style tmpStyle=(Style)dataGrid.FindResource(“ParameterTextBlockStyle”)仅此行并调试它。如果tmpStyle为NULL或抛出异常,我们可以尝试其他方法。