【问题标题】:Overriding a templated Button's Command in WPF在 WPF 中覆盖模板化按钮的命令
【发布时间】:2011-01-06 12:41:15
【问题描述】:

我有一个ControlTemplate,我用它来改变几个Buttons 的外观和行为。我只希望Button 的一部分可点击并执行绑定的Command,因此我在ControlTemplate 中添加了Button,并将其绑定到模板的Command 属性。

我遇到的问题是,由于我在模板化的Button 上定义了Command 绑定,因此无论我单击模板的哪个部分,它都会执行。

在下面的示例中,您可以单击Border 并执行Command。如何更改它以使 Command 仅在您单击模板中的 Button 时执行?

<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}" />

我认为我不能模板化不同的元素(例如 Border),因为我仍然需要以某种方式传入 Command,并且附加属性仍然会给我相同的行为。

【问题讨论】:

    标签: wpf templates xaml button command


    【解决方案1】:

    这是一个肮脏的技巧,但您可以将内部按钮的 Command 属性绑定到模板父级的 Tag 属性。这样您就可以从包含按钮中“隐藏”命令,但内部按钮秘密地知道如何访问它。

    您可以保留CommandParameter,因为它本身没有任何作用。

    【讨论】:

      【解决方案2】:

      另一种选择是重新模板化另一个控件,例如 Border 并在模板内的 Button 上使用 RoutedCommand。您可以将其绑定到内置 RoutedCommands 之一,例如 ApplicationCommands.Save,并在包含控件的 XAML 中,为该特定命令添加 CommandBinding。让我知道一些代码是否会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-14
        • 1970-01-01
        • 2011-05-24
        相关资源
        最近更新 更多