C# WPF 获取鼠标悬停在ListBox的Item上时的ListBoxItem的值。

private void ListBox2_MouseEnter(object sender, MouseEventArgs e)
        {
            StackPanel panel = e.OriginalSource as StackPanel;
            ListBoxItem parent = GetParentObject<ListBoxItem>(panel) as ListBoxItem;
            int index = ListBox2.ItemContainerGenerator.IndexFromContainer(parent);
            MessageBox.Show(index.ToString());

        }

        public T GetParentObject<T>(DependencyObject obj) where T : FrameworkElement
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);

            while (parent != null)
            {
                if (parent is T)
                {
                    return (T)parent;
                }

                parent = VisualTreeHelper.GetParent(parent);
            }
            return null;
        }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在WPF中实现鼠标悬停时出现下载按钮,可以使用以下步骤: 1. 在XAML中创建一个Image控件,将其Source属性设置为要显示的图片。 2. 将Image控件的IsMouseOver属性绑定到一个布尔,以便在鼠标悬停时更改其。 3. 使用VisualStateManager定义两个视觉状态:正常状态和鼠标悬停状态。在鼠标悬停状态下,添加一个Button控件作为下载按钮。 4. 将Image的模板应用于控件,并在模板中定义VisualStateManager。 以下是一个示例XAML代码: ```xml <Image Source="myImage.png"> <Image.Template> <ControlTemplate TargetType="Image"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="MouseOver"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="downloadButton" Storyboard.TargetProperty="(UIElement.Visibility)"> <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Image x:Name="image" Source="{TemplateBinding Source}" /> <Button x:Name="downloadButton" Content="Download" Visibility="Collapsed" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </ControlTemplate> </Image.Template> <Image.Style> <Style TargetType="Image"> <Setter Property="IsMouseOver" Value="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" /> </Style> </Image.Style> </Image> ``` 在此示例中,当鼠标悬停在图像上时,将显示一个名为“Download”的按钮。要更改按钮的外观和行为,请调整模板中的Button控件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值