【问题标题】:How a Line can Detect From canvas and Remove in WPF [closed]线条如何从画布中检测并在 WPF 中删除 [关闭]
【发布时间】:2017-04-15 09:24:25
【问题描述】:

我在Canvas 中有很多行。我只想检测哪一行被点击,并想从 WPF 中Canvas 的子级删除它?任何解决方案 谢谢。

【问题讨论】:

    标签: c# .net wpf xaml


    【解决方案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 操作。当按下 Delete 键时,选择应该被删除。

        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);
        }
    

    【讨论】:

    • 是的,感谢它的作品 :) :) 并帮助了很多@Anthony
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2021-10-07
    • 2016-07-05
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多