2017-04-15 68 views

回答

1

首先,您需要爲您的畫布添加一個MouseLeftButtonDown事件,爲您的WPF添加一個KeyDown事件。

public MainWindow() 
    { 
     InitializeComponent(); 
     MyCanvas.MouseLeftButtonDown += MyCanvas_MouseLeftButtonDown; 
     this.KeyDown += MainWindow_KeyDown; 
    } 

當您的鼠標左鍵單擊其中一條線時,應該突出顯示選擇。當點擊其他內容時,它應該取消選中之前的選擇。

private Line _selectedLine; 
    private void MyCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    { 
     object testPanelOrUi = InputHitTest(e.GetPosition(this)) as FrameworkElement; 

     // if the selection equals _selectedLine, i.e. the line has been selected already 
     if (Equals(testPanelOrUi, _selectedLine)) return; 

     // The selection is different. 
     // if _selectedLine is not null, revert color change. 
     if (_selectedLine != null) 
     { 
      UnHighlightSelection(); 
     } 

     // if testPanelOrUi is not a line. 
     if (!(testPanelOrUi is Line)) return; 

     // The selection is different and is a line. 
     _selectedLine = (Line) testPanelOrUi; 
     HighlightSelection(_selectedLine); 
    } 

HighlightSelection()UnHighlightSelection()可以類似於如下:

private void HighlightSelection(Line selectedob) 
    { 
     selectedob.Stroke = Brushes.Red; 
    } 

    private void UnHighlightSelection() 
    { 
     //if nothing has been selected yet. 
     if (_selectedLine == null) return; 

     _selectedLine.Stroke = Brushes.Black; 
     _selectedLine = null; 
    } 

然後,你可以定義你DeleteKeyDown行動。按下刪除鍵時,應該刪除選擇內容。

private void MainWindow_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Delete) 
     { 
      DeleteLine(); 
     } 
    } 

    public void DeleteLine() 
    { 
     //if nothing has been selected yet. 
     if (_selectedLine == null) return; 

     //if the selection has been deleted. 
     if (!MyCanvas.Children.Contains(_selectedLine)) return; 

     UnHighlightSelection(); 
     MyCanvas.Children.Remove(_selectedLine); 
    } 
+0

是啊感謝它的作品:) :)並幫助了很多@Anthony – Ahmad