如何正确地将一些自定义参数传递给WPF中的事件处理程序?

时间:2009-12-03 05:42:00

标签: wpf parameters event-handling

在WPF窗口(像矩形一样简单的对象)中为参数分配参数的正确方法是什么,并在鼠标点击时将它们传递给事件处理程序?

谢谢。

1 个答案:

答案 0 :(得分:1)

这是一种方式:

把它放在窗口中:

public static readonly RoutedUICommand clickCommand = new RoutedUICommand("TheCommand", "TheCommand", typeof(Window1));

void ClickRectangle(object sender, ExecutedRoutedEventArgs e)
{
    if (e.Parameter == null)
        return;
    MessageBox.Show("parameter = " + e.Parameter.ToString());
}

然后在XAML中:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:my="clr-namespace:WpfApplication1"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Rectangle Margin="50" Fill="Blue">
            <Rectangle.CommandBindings>
                <CommandBinding
                    Command="my:Window1.clickCommand" Executed="ClickRectangle" />
            </Rectangle.CommandBindings>
            <Rectangle.InputBindings>
                <MouseBinding MouseAction="LeftClick"
                              Command="my:Window1.clickCommand" CommandParameter="123" />
            </Rectangle.InputBindings>
        </Rectangle>
    </Grid>
</Window>