我有一个用DrawingContext绘制矩形的基础设施代码,我希望这些矩形有点击事件。我该怎么做呢?
这就是我画矩形的方法
dc.DrawRectangle(bg,笔划,矩形);
发布于 2011-01-20 18:11:35
那个矩形只是像素,它不能有任何事件。
您必须查看该DC的所有者(控制)。或者只使用Rectangle元素。
发布于 2011-01-20 18:12:16
您可以使用VisualTreeHelper的HitTest功能。类似这样的代码应该会对您有所帮助(当您在想要检查命中的位置单击鼠标时,执行此代码):
HitTestResult result = VisualTreeHelper.HitTest(this, mouselocation);
if (result.VisualHit.GetType() == typeof(DrawingVisual))
{
//do your magic here. result.VisualHit will contain the rectangle that got hit
}发布于 2011-01-20 19:25:21
您应该放置ItemsControl并将其ItemsSource属性绑定到矩形集合。然后,您应该重写ItemsControl.ItemTemplate并提供您自己的DataTemplate,其中包含显示矩形的自定义用户控件。此用户控件能够处理鼠标事件。
主窗口的XAML:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:self ="clr-namespace:Test"
Title="MainWindow"
Height="350" Width="700">
<Window.Resources>
<DataTemplate x:Key="RectTemplate">
<self:RectangleView />
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding Rectangles}"
ItemTemplate="{StaticResource RectTemplate}">
</ItemsControl>
</Grid>
和RectangleView:
<UserControl x:Class="Test.RectangleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" >
MainWindow背后的代码
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
public IEnumerable<Rect> Rectangles
{
get
{
yield return new Rect(new Point(10, 10), new Size(100, 100));
yield return new Rect(new Point(50, 50), new Size(400, 100));
yield return new Rect(new Point(660, 10), new Size(10, 100));
}
}
}和RectangleView背后的代码:
public partial class RectangleView : UserControl
{
public RectangleView()
{
InitializeComponent();
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
drawingContext.DrawRectangle(Brushes.Orchid, new Pen(Brushes.OliveDrab, 2.0), (Rect)this.DataContext);
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
// HERE YOU CAN PROCCESS MOUSE CLICK
base.OnMouseDown(e);
}
}我建议你多读一些关于ItemsControl,ItemContainers,DataTemplates和Styles的文章。
备注:由于时间限制,我将MainView和RectangleView的视图和模型逻辑合并到一个类中。在好的实现中,除了MainModel声明IEnumerable类型的属性之外,还应该有MainView的表示模型(MainModel)和RectangleView的表示模型(RectangleViewData)。因为RectangleViewData不关心属性的变化,所以MainModel可以控制它。
https://stackoverflow.com/questions/4745756
复制相似问题