2011-01-20 73 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可以控制它。