WPF在MouseEnter事件上修改UIElement

问题描述 投票:0回答:3

我使用WPF。我在边框内有一个Grid,我想在触发mouseEnter时让我的网格中显示一个按钮(否则看不见)。

我可以用e.GetPosition(myCanvas).X或Y来拖动这个边框来移动所有东西。

现在我尝试访问我网格中的按钮,让它显示,我卡住了。

在我的MouseEnter事件中,我做:

UIElement source = (UIElement)sender;

但我不能“分离”来源......没有儿童收藏。

有办法吗?

c# wpf shapes
3个回答
1
投票

Border类没有Children属性,但它有一个Child属性,如果Border的子节点实际上是Grid,则可以将其强制转换为Grid:

Border border = (Border)sender;
Grid grid = border.Child as Grid;
if (grid != null)
{
    Button button = grid.Children[0] as Button;
    if(button != null)
       button.Visibility = Visibility.Visible;
}

如果您正在处理Border元素的MouseEnter事件并且Border内的Grid包含Button元素,则此代码应该有效。如果您正在处理Grid的MouseEnter元素,您当然应该将sender参数直接转换为Grid。


0
投票

您可能希望在窗体上创建DependencyProperty,您可以将按钮的visibility属性绑定到。然后在边框的MouseEnter和MouseLeave中,设置DependencyProperty。


0
投票

我没想到在网格上做mouseenter。它就像魅力一样。我现在可以继续

Grid sourceG = (Grid)sender;
sourceG.Children[0].Visibility = Visibility.Visible;
© www.soinside.com 2019 - 2024. All rights reserved.