动态添加DataTemplate - 无法找到Converter的StaticResource [英] Dynamically added DataTemplate - StaticResource for Converter can't be found

查看:521
本文介绍了动态添加DataTemplate - 无法找到Converter的StaticResource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public void AddGridViewColumns()
{
GridView view =(GridView)_myListView.View;
GridViewColumn column = BuildGridViewColumn(1);
view.Columns.Add(column);
}

public virtual GridViewColumn BuildGridViewColumn(int blockIndex)
{
string templateXaml = string.Format(
@< DataTemplate
xmlns =http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x =http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local =clr-namespace:Pse.MyTest; assembly = MyTest>
< DataTemplate.Resources>
< local:BlockToBrushConverter
x:Key =_ blockToBrushConverter/>
< /DataTemplate.Resources>
< TextBlock
Style ={{StaticResource _gridViewCenterItemStyle}}
Text = {{Binding Path = Block {0} .ConditionLabel}}
Foreground ={{Binding Path = Block {0},Converter = {{StaticResource _blockToBrushConverter}}}}/>
< / DataTemplate>,
blockIndex);
System.Diagnostics.Debug.Print(templateXaml);
GridViewColumn column = new GridViewColumn();
column.Header = string.Format(Block {0},blockIndex);
column.CellTemplate =(DataTemplate)XamlReader.Parse(templateXaml);
返回列;
}

Debug.Print结果为:

 < DataTemplate 
xmlns =http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x =http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local =clr-namespace:Pse.MyTest; assembly = MyTest>
< DataTemplate.Resources>
< local:BlockToBrushConverter
x:Key =_ blockToBrushConverter/>
< /DataTemplate.Resources>
< TextBlock
Style ={StaticResource _gridViewCenterItemStyle}
Text ={Binding Path = Block1.ConditionLabel}
Foreground ={Binding Path = Block1,Converter = {StaticResource _blockToBrushConverter}}/>
< / DataTemplate>

当我运行它时,它表示找不到_blockToBrushConverter。



例外是:

  System.Windows.Markup.XamlParseException未处理
Message =找不到名为{_blockToBrushConverter}的资源。资源名称区分大小写。标记文件'MyTest; component / SetupWindowDictionary.xaml'中的对象'System.Windows.Data.Binding'错误行23位置13.
Source =PresentationFramework
LineNumber = 23
LinePosition = 13
NameContext =前景

如果我删除了Forecolor属性,XAML解析很好(我得到预期的结果)。看来在DateTemplate.Resources中包含转换器应该保证会被发现,但是由于某种原因,它不是。



我也尝试移动我的声明转换器资源在树中更高(到Window级别),但是也不起作用。似乎可以找到_gridViewCenterItemStyle,但由于某些原因,它拒绝找到转换器。



任何想法都非常感谢。






以下是堆栈跟踪的完整异常,以帮助您:

 code> System.Windows.Markup.XamlParseException未处理
Message =找不到名为{_blockToBrushConverter}的资源。资源名称区分大小写,对象System.Windows.Data.Binding中的错误标记文件'MyTest; component / SetupWindowDictionary.xaml'行23位置13.
Source =PresentationFramework
LineNumber = 23
LinePosition = 13
NameContext =Foreground
StackTrace:
在System.Windows.Markup.XamlParseException .ThrowException(String message,Exception innerException,Int32 lineNumber,Int32 linePosition,Uri baseUri,XamlObjectIds currentXamlObjectIds,XamlObjectIds contextXamlObjectIds,Type objectType)
在System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext,Int32 lineNumber,Int32 linePosition ,String message,Exception innerException)
在System.Windows.Markup.BamlRecordReader.ThrowExceptionWithLine(String message,Exception innerException)
在System.Windows.Markup.BamlRecordReader.ThrowException(String id,String parameter)
在System.Windows.StaticResourceExtension.ProvideValueInternal(IBamlReader bamlReader,Object targetObject,Object targetProperty,Boolean allowDeferredReference)
在System.Windows.StaticResour在System.Windows.Markup.BamlRecordReader.BaseReadOptimizedMarkupExtension(对象元素,Int16)上的
attributeId,PropertyDefinition propertyDefinition,Object value)
在System.Windows.Markup.BamlRecordReader.ReadPropertyWithStaticResourceIdRecord(BamlPropertyWithStaticResourceIdRecord bamlPropertyWithStaticResourceIdRecord)
在System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)
在系统.Windows.StyleHelper.LoadOptimizedTemplateContent(DependencyObject容器,ParserContext parserContext,OptimizedTemplateContent optimizedTemplateContent,FrameworkTemplate frameworkTemplate,IComponentConnector componentConnector,IStyleConnector styleConnector,List`1 affectedChildren,UncommonField`1 templatedNonFeChildrenField)
在System.Windows.FrameworkTemplate.LoadContent(DependencyObject容器,List`1 affectedChildren,UncommonField`1 templatedNonFeChildrenField)
在System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField,DependencyObject容器,FrameworkElementFactory templateRoot,Int32 lastChildIndex ,HybridDictionary childIndexFromChildID,FrameworkTemplate frameworkTemplate)
在System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField,FrameworkElement容器)
在System.Windows.FrameworkElement.ApplyTemplate()
在System.Windows System.Windows.UIElement.Measure(Size availableSize)
$ System.Windows.Controls.GridViewRowPresenter.MeasureOverride(Size约束)
在System.Windows .FrameworkElement.MeasureCore(Size availableSize)
在System.Windows.UIElement.Measure(Size availableSize)
(System.Windows.Controls.Border.MeasureOverride在System.Windows.Controls.Control.MeasureOverride(Size约束)
在System.Windows.FrameworkElement.MeasureCore(Size availableSize)
在System.Windows.UIElement.Measure(大小可用大小)
在System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size约束)
在System.Windows.FrameworkElement.MeasureCore(大小可用大小)
在System.Windows.UIElement.Measure(大小可用大小)
在MS.Internal.Helper.MeasureElementWithSingleChild(UIElement元素,大小约束)
在System.Windows.Controls.ItemsPresenter.MeasureOverride(大小约束)
在System.Windows.FrameworkElement.MeasureCore(大小可用大小)
在System.Windows.UIElement.Measur e(Size availableSize)
在MS.Internal.Helper.MeasureElementWithSingleChild(UIElement元素,大小约束)
在System.Windows.Controls.ScrollContentPresenter.MeasureOverride(大小约束)
在System.Windows在System.Windows.UIElement.Measure(Size availableSize)
$ System.Windows.Controls.DockPanel.MeasureOverride(Size约束)
在System.Windows .FrameworkElement.MeasureCore(Size availableSize)
在System.Windows.UIElement.Measure(Size availableSize)
在System.Windows.Controls.Grid.MeasureCell(Int32单元格,Boolean forceInfinityV)
在System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead,Size referenceSize,Boolean ignoreDesiredSizeU,Boolean forceInfinityV)
在System.Windows.Controls.Grid.MeasureOverride(大小约束)
在System.Windows.FrameworkElement .MeasureCore(Size availableSize)
在System.Windows.UIElement.Measure(Size availableSize)
在System.Windows.Controls.ScrollViewer.MeasureOverride(大小约束)
在System.Windows.FrameworkElement.MeasureCore(大小可用大小)
在System.Windows.UIElement.Measure(Size availableSize)
在System.Windows.Controls.Border.MeasureOverride(大小约束)
在System.Windows.FrameworkElement.MeasureCore(大小可用大小)
在System.Windows.UIElement.Measure(Size availableSize)
在System.Windows.Controls.Control.MeasureOverride(大小约束)
在System.Windows.FrameworkElement.MeasureCore(大小可用大小)
在System.Windows.UIElement.Measure(Size availableSize)
在System.Windows.Controls.Grid.MeasureOverride(大小约束)
在System.Windows.FrameworkElement.MeasureCore(大小可用大小)
在System.Windows.UIElement.Measure(Size availableSize)
在MS.Internal.Help在System.Windows.FrameworkElement.MeasureCore(Size availableSize)上的
$ System.Windows.Controls.ContentPresenter.MeasureOverride(Size约束)
在System.Windows.FrameworkElement.MeasureCore(大小可用大小)
在系统.Windows.UIElement.Measure(Size availableSize)
在System.Windows.ContextLayoutManager.UpdateLayout()
在System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
在System.Windows.Media .MediaContext.InvokeOnRenderCallback.DoWork()
在System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
在System.Windows.Media.MediaContext.RenderMessageHandlerCore(对象resizedCompositionTarget)
在System.Windows .MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
在System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调,Object args,Boolean isSingleParameter)
在System.Windows.Threading.Ex ceptionWrapper.TryCatchWhen(Object source,Delegate callback,Object args,Boolean isSingleParameter,Delegate catchHandler)
在System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback,Object args,Boolean isSingleParameter,Delegate catchHandler)
在System.Windows.Threading.DispatcherOperation.InvokeImpl()
在System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(对象状态)
在System.Threading.ExecutionContext.runTryCode(对象userData)
在System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode代码,CleanupCode backoutCode,Object userData)
在System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback回调,对象状态)
在System.Threading .ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state)
在System.Windows.Threading.DispatcherOperation.Invok System.Windows.Threading.Dispatcher.ProcessQueue()
在System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&处理)
在MS.Win32.HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&被处理)
在MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
在System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调,Object args,Boolean isSingleParameter)
在System.Windows.Threading.ExceptionWrapper.TryCatchWhen(对象源,委托回调,对象args,布尔isSingleParameter,委托catchHandler )
在System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback,Object args,Boolean isSingleParameter,Delegate catchHandler)
在System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority,TimeSpan timeout,Delegate方法,Object args,Boolean isSingleParameter)
在System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority,Delegate方法,Object arg)
在MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,I nt32 msg,IntPtr wParam,IntPtr lParam)
在MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
在System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame框架)
在System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame框架)
在System.Windows.Threading.Dispatcher System.Windows.Application.RunDispatcher(Object ignore)中的
$ System.Windows.Application.RunInternal(窗口窗口)
$ System.Windows.Application.Run(窗口中的
)窗口)
在System.Windows.Application.Run()
在Pse.TestExperiment.App.Main()在C:\Documents和Settings\Daniel Manes\My Documents\Projects\\ \\Cmd21\Team Map Experiment 2 \Solution\TestExperiment\obj\Debug\App.g.cs:line 0
在System.AppDomain._nExecuteAssembly(Assembly assembly,String [] args)
在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)
在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)
在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)
在System.Threading.ThreadHelper.ThreadStart ()
InnerException:

编辑:

问题解决:我在整个项目中进行了搜索,注意到我有一个额外的BlockToBrushConverter资源声明副本与同样的x:键入我的资源字典之一。一旦我消除了重复,问题就消失了。

解决方案

为了防止别人有一天看这个问题,出来,我在这个问题的顶部提出的代码实际上是有效的。错误是我的XAML中的其他地方有以下声明:

 < local:BlockToBrushConverter 
x:Key = _blockToBrushConverter/>

我相信这个重复阻止了资源被本地声明为动态DataTemplate(它不能创建一个相同名称的资源在相同的上下文中两次)。



对我来说,一些未解决的问题是为什么一些StaticResources需要在本地声明,而其他像_gridViewCenterItemStyle StaticResource一样)可以在树中声明得更高(如在Window级别)没有问题。


I'm using the following code to dynamically add columns to my GridView:

public void AddGridViewColumns()
{
    GridView view = (GridView)_myListView.View;
    GridViewColumn column = BuildGridViewColumn(1);
    view.Columns.Add(column);
}

public virtual GridViewColumn BuildGridViewColumn(int blockIndex)
{
    string templateXaml = string.Format(
        @"<DataTemplate
            xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
            xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
            xmlns:local=""clr-namespace:Pse.MyTest;assembly=MyTest"">
            <DataTemplate.Resources>
                <local:BlockToBrushConverter
                    x:Key=""_blockToBrushConverter"" />
            </DataTemplate.Resources>
            <TextBlock
                Style=""{{StaticResource _gridViewCenterItemStyle}}""
                Text=""{{Binding Path=Block{0}.ConditionLabel}}""
                Foreground=""{{Binding Path=Block{0}, Converter={{StaticResource _blockToBrushConverter}}}}"" />
        </DataTemplate>",
        blockIndex);
    System.Diagnostics.Debug.Print(templateXaml);
    GridViewColumn column = new GridViewColumn();
    column.Header = string.Format("Block {0}", blockIndex);
    column.CellTemplate = (DataTemplate)XamlReader.Parse(templateXaml);
    return column;
}

The Debug.Print results in:

<DataTemplate
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Pse.MyTest;assembly=MyTest">
    <DataTemplate.Resources>
        <local:BlockToBrushConverter
            x:Key="_blockToBrushConverter" />
    </DataTemplate.Resources>
    <TextBlock
        Style="{StaticResource _gridViewCenterItemStyle}"
        Text="{Binding Path=Block1.ConditionLabel}"
        Foreground="{Binding Path=Block1, Converter={StaticResource _blockToBrushConverter}}" />
</DataTemplate>

When I run it, it says it cannot find _blockToBrushConverter.

The exception is:

System.Windows.Markup.XamlParseException was unhandled
  Message="Cannot find resource named '{_blockToBrushConverter}'. Resource names are case sensitive.  Error at object 'System.Windows.Data.Binding' in markup file 'MyTest;component/SetupWindowDictionary.xaml' Line 23 Position 13."
  Source="PresentationFramework"
  LineNumber=23
  LinePosition=13
  NameContext="Foreground"

If I remove the Forecolor attribute, the XAML parses just fine (and I get the expected results). It seems like including the converter in DateTemplate.Resources should guarantee that it would be found, but for some reason it isn't.

I also tried moving the declaration for my converter resource higher in the tree (to the Window level), but that didn't work either. It seems to be able to find "_gridViewCenterItemStyle", but for some reason, it refuses to find the converter.

Any ideas greatly appreciated.


Here's the entire exception with stack trace in case it helps:

System.Windows.Markup.XamlParseException was unhandled
  Message="Cannot find resource named '{_blockToBrushConverter}'. Resource names are case sensitive.  Error at object 'System.Windows.Data.Binding' in markup file 'MyTest;component/SetupWindowDictionary.xaml' Line 23 Position 13."
  Source="PresentationFramework"
  LineNumber=23
  LinePosition=13
  NameContext="Foreground"
  StackTrace:
       at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType)
       at System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException)
       at System.Windows.Markup.BamlRecordReader.ThrowExceptionWithLine(String message, Exception innerException)
       at System.Windows.Markup.BamlRecordReader.ThrowException(String id, String parameter)
       at System.Windows.StaticResourceExtension.ProvideValueInternal(IBamlReader bamlReader, Object targetObject, Object targetProperty, Boolean allowDeferredReference)
       at System.Windows.StaticResourceExtension.ProvideValue(IServiceProvider serviceProvider)
       at System.Windows.Markup.BamlRecordReader.ProvideValueFromMarkupExtension(MarkupExtension markupExtension, Object obj, Object member)
       at System.Windows.Markup.BamlRecordReader.BaseReadOptimizedMarkupExtension(Object element, Int16 attributeId, PropertyDefinition propertyDefinition, Object value)
       at System.Windows.Markup.BamlRecordReader.ReadPropertyWithStaticResourceIdRecord(BamlPropertyWithStaticResourceIdRecord bamlPropertyWithStaticResourceIdRecord)
       at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)
       at System.Windows.StyleHelper.LoadOptimizedTemplateContent(DependencyObject container, ParserContext parserContext, OptimizedTemplateContent optimizedTemplateContent, FrameworkTemplate frameworkTemplate, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
       at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
       at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
       at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
       at System.Windows.FrameworkElement.ApplyTemplate()
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.GridViewRowPresenter.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.Border.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.Control.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint)
       at System.Windows.Controls.ItemsPresenter.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint)
       at System.Windows.Controls.ScrollContentPresenter.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.DockPanel.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.Grid.MeasureCell(Int32 cell, Boolean forceInfinityV)
       at System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV)
       at System.Windows.Controls.Grid.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.ScrollViewer.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.Border.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.Control.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.Controls.Grid.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint)
       at System.Windows.Controls.ContentPresenter.MeasureOverride(Size constraint)
       at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
       at System.Windows.UIElement.Measure(Size availableSize)
       at System.Windows.ContextLayoutManager.UpdateLayout()
       at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
       at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
       at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
       at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
       at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at Pse.TestExperiment.App.Main() in C:\Documents and Settings\Daniel Manes\My Documents\Projects\Cmd21\Team Map Experiment 2\Solution\TestExperiment\obj\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

EDIT:

Problem solved: I did a search through my whole project and noticed I had an extra copy of the BlockToBrushConverter resource declaration with same x:Key in one of my resource dictionaries. Once I eliminated the duplication, the problem disappeared.

解决方案

Just in case someone else takes a look at this question someday, it turns out, the code I presented at the top of this question actually works. The bug was that I had the following declaration elsewhere in my XAML:

<local:BlockToBrushConverter
    x:Key="_blockToBrushConverter" />

I believe this duplication prevented the resource from being declared locally for the dynamic DataTemplate (it couldn't create a resource with the same name twice within the same context).

One thing that is sort of unresolved for me is why some StaticResources need to be declared locally, while others (like the _gridViewCenterItemStyle StaticResource) can be declared higher in the tree (such as at the Window level) without a problem.

这篇关于动态添加DataTemplate - 无法找到Converter的StaticResource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆