【问题标题】:MouseEventArgs with undesired namespace具有不需要的命名空间的 MouseEventArgs
【发布时间】:2018-09-04 19:35:04
【问题描述】:

最终目标是为 ListBox 中的对象添加工具提示。我发现了一些这样做的例子,即:

private void OnListBoxMouseMove ( object sender, MouseEventArgs e )
{
    string strTip = "";

    // Get the item
    int nIdx = listBox1.IndexFromPoint(e.Location);

    if ((nIdx >= 0) && (nIdx < listBox1.Items.Count))
        strTip = listBox1.Items[nIdx].ToString();

    toolTip1.SetToolTip(listBox1, strTip);
}

但是,我的页面将其作为System.Windows.Input.MouseEventArgs 对象而不是Systems.Windows.Forms 放入,因此e.Location 不存在。

是否可以从正确的命名空间接收此事件?另一个因素可能是 ListBox 在 System.Windows.Controls 命名空间中?

【问题讨论】:

  • 这可能有用 - GetPosition
  • System.Windows.Input 是 wpf,System.Windows.Forms 是 winforms。您要么使用其中一个,要么使用另一个,但很少将两者结合在一个窗口中。
  • 您正在开发 WPF 或 Windows 窗体应用程序吗?

标签: c# wpf winforms


【解决方案1】:

为了完成最终目标,为列表框中的每个单独项目添加工具提示,我只是将事件处理程序添加到 xmal 中的列表框。

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
         <EventSetter Event="MouseEnter" Handler="mouseEnterMethodName"></EventSetter>
    </Style>
</ListBoxItemTemplate>

然后在 cs 中简单地将发件人转换为 ListBoxItem,然后将 ListBoxItem.ToolTip 设置为您想要的任何内容。了解 WPF 和 winforms 在不同的命名空间中工作非常有用。谢谢大家!

【讨论】:

    【解决方案2】:

    我相信您正在使用 WPF,这应该是您正在寻找的答案:

    Displaying a tooltip text on a listbox specific item

    文章正文:

    您好,如果您想在 ListBox 中的单个项目上显示工具提示,这里有一个快速简单的方法。它不需要自定义控件,而且代码相当小。

    首先创建一个处理鼠标移动事件的方法,然后将它与 ListBox 的 MouseMove 事件挂钩。您还需要一个 ToolTip 对象作为表单的成员变量。创建和更新工具提示所需的代码是:

    private void onMouseMove(object sender, MouseEventArgs e)
    {
        if(sender is ListBox)
        {      
            ListBox listBox = (ListBox)sender;
            Point point = new Point(e.X, e.Y);
            int hoverIndex = listBox.IndexFromPoint(point);
            if(hoverIndex >= 0 && hoverIndex < listBox.Items.Count)
            {
                tt.SetToolTip(listBox, listBox.Items[hoverIndex].ToString());
            } 
        }    
    }
    

    更多信息,请查看end of this article

    对于第二个问题,您可以使用ToolTip.AutomaticDelay Property

    【讨论】:

    • 一个基本上只显示指向另一个站点/页面的链接的答案并不是最好的事情,尤其是如果解决方案很短并且可以写在这里。您最好告诉您从中获取答案的页面,但也可以直接编写解决方案,这样用户就不需要到处跳来寻找他们正在搜索的内容。另请注意,您编写的链接可能会及时丢失,而此处编写的解决方案仍然有效!
    • @marco 感谢您告诉我实际上我认为它会将其视为评论,但网站将其作为答案进行了检查
    • 好吧,您仍然可以编辑您的答案尝试改进它:)
    • 不幸的是,该示例似乎使用了其他 Forms 命名空间。我可以使用 e.GetPosition 来获取一个点,而不是使用 e.X 和 e.Y,但是 IndexFromPoint 我还没有找到一个等价物
    猜你喜欢
    • 1970-01-01
    • 2012-10-16
    • 2011-08-15
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多