我有ResourceDictionary
,其中包含DataTemplate
。在這個DataTemplate的資源中,我聲明瞭一個CommandBindingCollection
。我的ResourceDictionary有一個代碼隱藏文件,我在其中聲明處理程序爲Executed/CanExecute。ResourceDictionary中的DataTemplate中的CommandBinding,處理程序未正確分配
我遇到的問題是,當我從ResourceDictionary
中檢索我的CommandBindingCollection
時,未分配已執行/可執行處理程序。使用調試器,我可以看到處理程序爲空。爲什麼是這樣的,我該如何解決它?
ResourceDictionary的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/>
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
到pply 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;
然後處理程序的設置是否正確。我想知道爲什麼當我在DataTemplate的資源中聲明它時,它不能設置事件處理程序的委託。
試試看看這個類似的問題:http://stackoverflow.com/questions/5632698/execute-command-does-not-fire-in-resource-dictionary-code-behind – Johnny
@Johnny是啊已經有一個看看它,但該解決方案不適用於我的特殊情況(我的CommandBindingCollection位於ResourceTictionary本身內的Datatemplate的資源內) –
通過從資源字典中檢索命令綁定,這意味着什麼。要分配命令綁定到什麼控件?你能告訴我們TestCommands的源代碼嗎?如何分配數據模板? – Per