【发布时间】:2017-04-15 09:24:25
【问题描述】:
我在Canvas 中有很多行。我只想检测哪一行被点击,并想从 WPF 中Canvas 的子级删除它?任何解决方案
谢谢。
【问题讨论】:
我在Canvas 中有很多行。我只想检测哪一行被点击,并想从 WPF 中Canvas 的子级删除它?任何解决方案
谢谢。
【问题讨论】:
首先,您需要为您的画布添加一个 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;
}
然后您可以定义您的Delete 和KeyDown 操作。当按下 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);
}
【讨论】: