【问题标题】:How to correctly pass some custom parameters to event handlers in WPF?如何正确地将一些自定义参数传递给 WPF 中的事件处理程序?
【发布时间】:2009-12-03 05:41:59
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: wpf parameters event-handling


    【解决方案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>
    

    【讨论】:

    • 谢谢。你能告诉我,有没有办法将这样的参数嵌入到代表这个矩形的自定义控件中,以便在我们有数百个这样的矩形的情况下优化代码? (这样我们只为每个矩形的参数赋值)。
    • 我认为您在谈论依赖属性...查找它们,看看是否可以让它们为您工作 - 如果没有,您可以发布另一个问题 :)
    • 谢谢。你帮了我很多。我现在正在查找依赖属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2011-05-02
    • 1970-01-01
    • 2012-08-30
    • 2018-12-05
    相关资源
    最近更新 更多