ControlTemplate のボタン コマンドを CustomControl の Execute() メソッドにバインドしています。RoutedCommand を使用しています。CanExecute() は起動しますが、Execute() は起動しません。CustomControl がメイン ウィンドウに配置されると、コードは期待どおりに機能します。ユーザーコントロールに配置すると、この問題が発生します。ボタン コマンド (RelayCommand など) を接続する方法をいくつか試しましたが、何が問題なのかわかりません。どんな助けでも大歓迎です。
文脈上、これは 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 から継承します。非静的コンストラクターでは、静的削除コマンドを DeleteToken メソッドに接続します。
public TokenizedTextBox()
{
CommandBindings.Add(new CommandBinding(TokenizedTextBoxCommands.Delete, DeleteToken, CanDelete));
}
最後に、CanExecute を true に設定するだけの CanDelete:
private void CanDelete(object sender, CanExecuteRoutedEventArgs canExecuteRoutedEventArgs)
{
canExecuteRoutedEventArgs.CanExecute = true;
}
そして DeleteToken - 機能は省略されています。署名はここで本当に重要なものだけです:
private void DeleteToken(object sender, ExecutedRoutedEventArgs e)
{
...
}
したがって、これがガイダンス/提案を提供することに関心のある人にとって十分な情報であることを願っています. ありがとう。