[英]WPF - How to add a click event to an items control?
我有这个 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>
它只是在屏幕上绘制正方形。 我想要一个事件,以便当我单击它调用该事件的一个正方形时,我还需要获取我单击的 object(模板的数据类型是 Square class 并且整个网格绑定到一个可观察的集合称为Board
),我该怎么做?
将矩形放在一个Button的模板中,并处理该按钮的点击事件。 请记住将矩形的填充设置为透明,否则将无法检测到在按钮填充区域中的鼠标单击。
<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
}
最好给Square
一个命令属性,并将 Button.Command 绑定到该属性:
public class Square
{
// stuff
public ICommand SelectCommand { get; } // Initialize in constructor
// stuff
}
<Button Command="{Binding SelectCommand}">
<!-- ...as before... -->
但是随后您需要实现 ICommand 等。 Click 事件运行良好。
您还可以在 Rectangle 本身上处理 MouseLeftButtonDown。 您仍然必须将其填充设置为透明。 我更喜欢这个解决方案,因为单击行为比 MouseLeftButtonDown 更复杂:例如,当您将鼠标放在按钮上并在释放鼠标按钮之前拖出按钮时,不会引发 Click。 用户已经习惯了这种行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.