Overriding a templated Button's Command in WPF

旧街凉风 提交于 2019-12-10 17:22:50

问题


I have a ControlTemplate that I'm using to change the appearance and behavior of several Buttons. I only want part of the Button to be clickable and to execute the bound Command, so I added a Button within the ControlTemplate and bound it to the template's Command property.

The problem I'm having is that since I am defining the Command binding on the templated Button, it executes regardless of which part of the template I am clicking.

In the below example you can click the Border and execute the Command. How do I change it so that the Command only executes when you click the Button within the template?

<ControlTemplate x:Key="ButtonControlTemplate" TargetType="{x:Type Button}">
    <Border BorderThickness="10" BorderBrush="Black">
        <Button
            Command="{TemplateBinding Command}"
            CommandParameter="{TemplateBinding CommandParameter}" >
            <ContentPresenter Content="{TemplateBinding Content}" />
        </Button>
    </Border>
</ControlTemplate>

...

<Button
    Command="{Binding Path=SomeViewmodelCommand}"
    CommandParameter="{Binding Path=SomeViewmodelCommandParameter}"
    Content="Click"
    Template="{StaticResource ButtonControlTemplate}" />

I don't think I can template a different element (like the Border) because I still need to pass in the Command somehow, and attached properties would still give me the same behavior.


回答1:


It's a dirty hack, but you can bind the inner button's Command property to the templated parent's Tag property instead. That way you 'hide' the command from the containing button, but the inner button secretly knows how to get to it.

You can leave the CommandParameter as is, since it has no effect by itself.




回答2:


Another alternative is to re-template another control, such as Border and use a RoutedCommand on the Button inside the template. You could bind it to one of the built-in RoutedCommands, such as ApplicationCommands.Save and in the XAML for the containing control, add a CommandBinding for that particular command. Let me know if some code would be helpful.



来源:https://stackoverflow.com/questions/2088876/overriding-a-templated-buttons-command-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!