我將ControlTemplate中的按鈕命令綁定到CustomControl中的Execute()方法。我使用的是RoutedCommand,CanExecute()會觸發,但Execute()從來不會。當CustomControl放置在主窗口中時,代碼按預期工作。當它被放置在Usercontrol中時,我遇到了這個問題。我嘗試了幾種方法來連接按鈕命令(RelayCommand等),但似乎無法弄清楚什麼是錯的。任何幫助表示讚賞。CustomControl中的命令綁定問題:CanExecute()觸發,Execute()不會
對於上下文,這是一個TokenizingTextBox控件--Xceed開源版本的早期版本。該按鈕用於從令牌列表中刪除令牌。
一個TokenIten(包含感興趣的按鈕)的完整風格:
<Style TargetType="{x:Type local:TokenItem}">
<Setter Property="Background" Value="#F3F7FD" />
<Setter Property="BorderBrush" Value="#BBD8FB" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Cursor" Value="Arrow" />
<Setter Property="Padding" Value="2,1,1,1" />
<Setter Property="Margin" Value="1,0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TokenItem}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}"
CornerRadius="0,0,5,5"
Margin="{TemplateBinding Margin}"
>
<StackPanel Orientation="Horizontal" Margin="1" x:Name="myRoot">
<ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" />
<Button Margin="3,0,0,0" Cursor="Hand"
Command="{x:Static local:TokenizedTextBoxCommands.Delete}" CommandParameter="{TemplateBinding TokenKey}"
PresentationTraceSources.TraceLevel="High">
<!--<Button.Template>
<ControlTemplate TargetType="Button">
<ContentPresenter />
</ControlTemplate>
</Button.Template>-->
<Image Source="/Resources/delete8.png" Width="8" Height="8" />
</Button>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
靜態命令:
public static class TokenizedTextBoxCommands
{
private static RoutedCommand _deleteCommand = new RoutedCommand();
public static RoutedCommand Delete => _deleteCommand;
}
自定義控件自ItemsControl繼承。在非靜態構造函數,我們連線了靜態delete命令到DeleteToken方法:
public TokenizedTextBox()
{
CommandBindings.Add(new CommandBinding(TokenizedTextBoxCommands.Delete, DeleteToken, CanDelete));
}
最後CanDelete這只是設置CanExecute爲true:
private void CanDelete(object sender, CanExecuteRoutedEventArgs canExecuteRoutedEventArgs)
{
canExecuteRoutedEventArgs.CanExecute = true;
}
而且DeleteToken - 省略的功能,簽名這裏真的只有重要的事情:
private void DeleteToken(object sender, ExecutedRoutedEventArgs e)
{
...
}
所以,希望這是有興趣提供指導/建議的任何人的足夠的信息。謝謝。