我有一個Grid
控制到我動態添加,看起來行,如下所示:WPF:保持矩形填充顏色上的mouseenter /鼠標離開
我想強調的是具有鼠標光標的行超過它。我目前正在通過在該行添加一個Rectangle
作爲背景,並在MouseEnter
和MouseLeave
上更改其Fill
屬性。
Rectangle rect = new Rectangle();
Grid.SetRow(rect, rowNum);
Grid.SetColumn(rect, colNum);
Grid.SetColumnSpan(rect, dataGrd_.ColumnDefinitions.Count);
rect.Fill = new SolidColorBrush(Colors.White);
rect.MouseEnter += Rect_MouseEnter;
rect.MouseLeave += Rect_MouseLeave;
dataGrd_.Children.Add(rect);
private void Rect_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
(sender as Rectangle).Fill = new SolidColorBrush(Colors.White);
}
private void Rect_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
(sender as Rectangle).Fill = new SolidColorBrush(Colors.Yellow);
}
的問題是,當在該行的前景控件的一個鼠標移動時,觸發MouseLeave
事件和突出丟失。
只要鼠標位於Rectangle
的範圍內,是否有突出顯示的方法,即使它位於前景控件上?
另外,MouseEnter
事件在鼠標進入該行但未超過Label
或其他控件時未觸發。我想我可以添加事件處理程序到所有的控件,但這聽起來過度。
因爲我是動態添加這些行的,所以我真的只對解決方案後面的代碼感興趣,除非有辦法在XAML中實現我的功能。
爲什麼你不使用ListBox控件,ItemSourse綁定到ObservableCollection?這樣你就可以在添加/刪除時獲得動態行更新,並免費獲得行高亮(更不用說你的代碼對其他人來說是可以理解的)。 –
@swiszcz我猜想真正的答案是我不是C#開發人員,所以這個解決方案對我來說並不明顯。我會考慮使用'ListBox',所以我很欣賞提示。 –
@swiszcz從我所知道的情況來看,'ListBox'控件只會突出顯示所選行,而不是鼠標懸停。 –