C# 使命令仅在窗口的一部分工作

C# 使命令仅在窗口的一部分工作,c#,wpf,routed-commands,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"

我有这个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>

如您所见,窗口中有一个名为Cmd的命令。窗口中有两个矩形-黄色和绿色。我希望命令Cmd仅在鼠标单击黄色矩形时才起作用,但在绿色矩形中不起作用。如何实现这一点?

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

<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>

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

而不是

<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>

使用



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

实际上我需要一些相反的东西-该命令应该适用于黄色矩形(基本上变成黄色框架),并且它应该忽略绿色矩形(内部矩形)内的单击,因此它就像一个边框。当您单击边框时,会执行命令,但当您在边框内单击时,它不会执行任何操作。我尝试将命令绑定到外部矩形,但仍然会对内部矩形执行命令。那不是我想要的。我明白了,那么你可以使用DHN的解决方案。我发现类似的文章很难。
<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>