2017-09-14 102 views
-1

我有一個Grid控制到我動態添加,看起來行,如下所示:WPF:保持矩形填充顏色上的mouseenter /鼠標離開

enter image description here

我想強調的是具有鼠標光標的行超過它。我目前正在通過在該行添加一個Rectangle作爲背景,並在MouseEnterMouseLeave上更改其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中實現我的功能。

+0

爲什麼你不使用ListBox控件,ItemSourse綁定到ObservableCollection?這樣你就可以在添加/刪除時獲得動態行更新,並免費獲得行高亮(更不用說你的代碼對其他人來說是可以理解的)。 –

+0

@swiszcz我猜想真正的答案是我不是C#開發人員,所以這個解決方案對我來說並不明顯。我會考慮使用'ListBox',所以我很欣賞提示。 –

+0

@swiszcz從我所知道的情況來看,'ListBox'控件只會突出顯示所選行,而不是鼠標懸停。 –

回答

0

你可以保持到Rectangle參考:

private Rectangle rect; 
void ...() 
{ 
    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); 
    dataGrd_.MouseEnter += dataGrd__MouseEnter; 
    dataGrd_.MouseLeave += dataGrd__MouseLeave; 
} 

...和處理父Grid這樣的相同事件:

private void dataGrd__MouseEnter(object sender, MouseEventArgs e) 
{ 
    Point p = e.GetPosition(rect); 
    if (p.X > 0 && p.X <= rect.ActualWidth && p.Y > 0 && p.Y <= rect.ActualHeight) 
     rect.Fill = new SolidColorBrush(Colors.Yellow); 
} 

private void dataGrd__MouseLeave(object sender, MouseEventArgs e) 
{ 
    Point p = e.GetPosition(rect); 
    if (p.X < 0 || p.X > rect.ActualWidth || p.Y < 0 || p.Y > rect.ActualHeight) 
     rect.Fill = new SolidColorBrush(Colors.White); 
} 
+0

每行有1個矩形,所以不知道這個解決方案如何工作。 –

+0

然後處理該行的MouseEnter/MouseLeave事件。 – mm8