资源字典中的数据模板中的命令绑定,未正确分配处理程序



我有一个ResourceDictionary,其中包含一个DataTemplate。在此数据模板的资源中,我声明了一个CommandBindingCollection。我的资源字典有一个代码隐藏文件,我在其中声明了 Executed/CanExecute 的处理程序。

我遇到的问题是,当我从ResourceDictionary中检索CommandBindingCollection时,未分配已执行/可以执行处理程序。使用调试器,我可以看到处理程序为空。为什么会这样,我该如何解决?

资源字典 XAML:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="Test"
                    x:Class="Test.MyResourceDictionary">
    <DataTemplate x:Key="Template"
                  x:Name="Template">
        <DataTemplate.Resources>
            <CommandBindingCollection x:Key="CommandBindings">
                <CommandBinding Command="local:TestCommands.Test"
                        Executed="testExecuted" 
                        CanExecute="testCanExecute" />
            </CommandBindingCollection>
        </DataTemplate.Resources>
        <!-- More stuff here -->
    </DataTemplate>
<ResourceDictionary/>

资源字典代码隐藏:

public partial class MyResourceDictionary: ResourceDictionary
{
    public MyResourceDictionary() 
    { 
        InitializeComponent(); 
    } 
    private void testExecuted(object sender, ExecutedRoutedEventArgs e)
    {
    }
    private void testCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
    }
}

更新

我正在将其与AvalonDock一起使用,它使用DataTemplateSelector来应用DataTemplate。

以下是我加载模板的方式:

public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
    if (item is TestViewModel)
    {
        ResourceDictionary res = Application.LoadComponent(new Uri("/MyResourceDictionary.xaml", UriKind.Relative)) as ResourceDictionary;
        DataTemplate template = res["Template"] as DataTemplate;
        if(template != null)
        {
            CommandBindingCollection commandBindings = 
                template.Resources["CommandBindings"] as CommandBindingCollection;
            if(commandBindings != null)
            {
                foreach(var binding in commandBindings)
                {
                     // add commandbinding to the container control
                     // here, using the debugger i can see that the handlers for the commandbinding
                     // are always null (private variables that I can only see using debugger)
                }
            }
            return template;
        }
    }
    return base.SelectTemplate(item, container);
}

如果我将CommandBindingCollection直接移动到ResourceDictionary中并以这种方式访问它:

CommandBindingCollection commandBindings = 
            res["CommandBindings"] as CommandBindingCollection;

然后正确设置处理程序。我想知道为什么当我在数据模板的资源中声明事件处理程序时,它无法设置事件处理程序的委托。

我的问题与 .NET 框架中的一个错误有关,该错误似乎在 4.5 中得到了修复。

4.0 上有一个修补程序:http://support.microsoft.com/kb/2464222

就我而言,应用此修复程序解决了问题。我的猜测是,在 CommandBindingCollection XAML 解析器中的某个地方,异常是静默处理的。

最新更新