0

我有这个 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 仅在鼠标单击黄色矩形而不是绿色矩形时才起作用。我怎样才能做到这一点?

4

2 回答 2

0

听起来您应该将黄色矩形放在 a 上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>

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

于 2013-03-19T09:20:28.643 回答
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 一起使用。

于 2013-03-19T09:20:52.807 回答