Reputation: 89
I have this ItemsControl:
<ItemsControl Grid.Row="1" ItemsSource="{Binding Board}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="local:Square">
<Rectangle Stroke="Blue" StrokeThickness="0.5" Width="{Binding Width}" Height="{Binding Height}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
and it simply draws squares onto the screen. I want an event so that when I click on one of the squares it calls that event, I need to also get the object I clicked on (the data type of the template is a Square class and the entire grid is bound to an observable collection called Board
), how could I do that?
Upvotes: 0
Views: 1825
Reputation: 37057
Put the rectangle in the template of a Button and handle the button's click event. Remember to set the rectangle's Fill to Transparent, or else mouse clicks in the fill area of the button won't be detected.
<Button Click="Rectangle_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<Rectangle
Fill="Transparent"
Stroke="Blue"
StrokeThickness="0.5"
Width="{Binding Width}"
Height="{Binding Height}"
/>
</ControlTemplate>
</Button.Template>
</Button>
private void Rectangle_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var square = button.DataContext as Square;
// Do whatever
}
It would be preferable to give Square
a command property, and bind Button.Command to that:
public class Square
{
// stuff
public ICommand SelectCommand { get; } // Initialize in constructor
// stuff
}
<Button Command="{Binding SelectCommand}">
<!-- ...as before... -->
But then you need to implement ICommand, etc. The Click event works well enough.
You could also handle MouseLeftButtonDown on the Rectangle itself. You'd still have to set its Fill to Transparent. I prefer this solution because Click behavior is more complicated than MouseLeftButtonDown: For example, when you mouse down on a button and drag out of the button before releasing the mouse button, Click isn't raised. Users are accustomed to that behavior.
Upvotes: 1