使命令仅在窗口的一部分中起作用

时间:2013-03-19 08:45:34

标签: c# wpf routed-commands

我有这个xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:this="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525" Name="this">
    <Grid>
        <Grid.CommandBindings>
            <CommandBinding Command="{x:Static this:MainWindow.Cmd}" Executed="CommandBinding_Executed"/>
        </Grid.CommandBindings>
        <Grid.InputBindings>
            <MouseBinding Command="{x:Static this:MainWindow.Cmd}" MouseAction="LeftClick"/>
        </Grid.InputBindings>
        <Rectangle Fill="Yellow"/>
        <Rectangle Fill="Green" Margin="50">
            <Rectangle.InputBindings>
                <MouseBinding Command="NotACommand" MouseAction="LeftClick"/>
            </Rectangle.InputBindings>
        </Rectangle>
    </Grid>
</Window>

和这个代码隐藏文件:

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        static RoutedCommand cmd = new RoutedCommand();

        public static RoutedCommand Cmd
        {
            get { return MainWindow.cmd; }
            set { MainWindow.cmd = value; }
        }

        public MainWindow()
        {
            InitializeComponent();
        }
        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Cmd");
        }
    }
}

正如您所看到的,窗口中有一个名为Cmd的命令。窗口内有2个矩形 - 黄色和绿色。我希望命令Cmd仅在鼠标单击黄色矩形时工作,而不是绿色矩形。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

听起来你应该将黄色矩形放在Button上,然后直接将命令分配给它。例如。像这样。

<Button Command="YourCommandHere">
    <RecTangle Fill="Yellow" />
    <!-- let your button look and behave like the rectangle -->
    <Button.Template>
        <ControlTemplate x:TargetType="Button">
            <ContentPresenter Content="{TemplateBinding Content}" />
        </ControlTemplate>
    </Button.Template>
</Button>

我认为这是最干净的方式。

答案 1 :(得分:0)

而不是

<Grid.CommandBindings>
    <CommandBinding Command="{x:Static this:MainWindow.Cmd}" Executed="CommandBinding_Executed"/>
</Grid.CommandBindings>
<Grid.InputBindings>
    <MouseBinding Command="{x:Static this:MainWindow.Cmd}" MouseAction="LeftClick"/>
</Grid.InputBindings>

使用

<Rectangle Fill="Green" Margin="50">
    <Rectangle.InputBindings>
        <MouseBinding Command="{x:Static this:MainWindow.Cmd}" MouseAction="LeftClick"/>
    </Rectangle.InputBindings>
</Rectangle>

也许确实需要一些调整来确保绑定和命令。我个人不使用这种直接方法。我通常将ViewModel与DataContext一起使用。