C# WPF-如何将单击事件添加到items控件?

C# WPF-如何将单击事件添加到items控件?,c#,wpf,events,C#,Wpf,Events,我有此项控件: <ItemsControl Grid.Row="1" ItemsSource="{Binding Board}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <WrapPanel IsItemsHost="True"/> </ItemsPanelTemplate> </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>

它只是在屏幕上画正方形。我想要一个事件,当我点击其中一个称为该事件的方块时,我还需要得到我点击的对象模板的数据类型是一个方块类,整个网格绑定到一个称为Board的可观察集合,我该怎么做呢?

将矩形放在按钮的模板中,并处理按钮的单击事件。请记住将矩形的填充设置为透明,否则将无法检测到鼠标单击按钮填充区域

<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>
最好为Square提供一个命令属性,并将Button.command绑定到该属性:

public class Square
{
    //  stuff

    public ICommand SelectCommand { get; } // Initialize in constructor

    //  stuff
}
但是,您需要实现ICommand等。单击事件可以很好地工作

您还可以在矩形本身上处理MouseLeftButtonDown。您仍然需要将其填充设置为透明。我更喜欢这个解决方案,因为单击行为比MouseLeftButtonDown更复杂:例如,当您在 在释放鼠标按钮之前,将一个按钮拖出该按钮,单击不会升起。用户习惯于这种行为

public class Square
{
    //  stuff

    public ICommand SelectCommand { get; } // Initialize in constructor

    //  stuff
}
<Button Command="{Binding SelectCommand}">
<!-- ...as before... -->