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