2011-01-20 30 views
0

我有一个使用DrawingContext绘制矩形的基础结构代码,我希望那些矩形有点击事件。我怎样才能做到这一点 ?在DrawingContext中实现选择

这是怎么绘制矩形

dc.DrawRectangle(BG,中风,RECT);

回答

1

该矩形只是像素,它不能有任何事件。

你必须看看该DC的所有者(控制)。或者只是使用一个Rectangle元素。

0

您可以使用VisualTreeHelperHitTest功能。像这样的东西应该帮助你(当你点击鼠标的地方,你要检查命中执行此代码):

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 
} 
+0

Rect不会命中。这不是视觉。 – 2011-01-20 10:34:08

0

您应该将ItemsControl的其ItemsSource属性绑定到矩形的集合。 然后您应该重写ItemsControl.ItemTemplate并提供您自己的DataTemplate,其中包含显示Rectangle的自定义用户控件。这个用户控件能够处理鼠标事件。

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

代码后面主窗口

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和样式。

P.S.由于时间限制,我将视图和模型逻辑合并为MainView和RectangleView的一个类。在良好的实现中,除了MainModel声明IEnumerable类型的属性之外,您应该具有MainView(MainModel)的表示模型和RectangleView(RectangleViewData)的表示模型。由于RectangleViewData不关心属性更改,MainModel可以控制它。