views:

378

answers:

1

What could be a correct way to assign parameters to objects in WPF window (objects as simple as rectangles) and pass them to event handlers on mouse clicks?

Thank you.

+1  A: 

Here's one way:

Put this in the Window:

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());
}

Then in the 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>
IanR
Thank you. Could you please tell, is there a way to embed such parameter in a custom control representing this rectangle in order to optimize code in case we have hundreds of such rectangles? (So that we only assign a value to each rectangles' parameter).
rem
I think you are talking about Dependecy Properties... look them up and see if you can get them to work for you - if not, you can post another question :)
IanR
Thank you. You helped me a lot. I am now looking up Dependency Properties.
rem