在rutime添加WPF菜单项-如何指定单击事件处理程序? [英] Adding a WPF menuitem at rutime -- how to specify a click event handler?

查看:516
本文介绍了在rutime添加WPF菜单项-如何指定单击事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

我正在自学WPF,并正在慢慢构建我的第一个应用程序,所以请耐心等待.

我有一个名为sProjectList的数组,之后将menuitems添加到菜单中,这很好用:

Hi all!

I am teaching myself WPF and slowly building my first application, so please be patient.

I have an array, named sProjectList, after which I add menuitems to a menu, this is working fine:

Dim x As Integer
...
If IsArray(sProjectList) Then
    For i = sProjectList.GetLowerBound(0) To sProjectList.GetUpperBound(0)
        x = miProjectList.Items.Add(sProjectList(i, 0).ToString)
    Next i
End If



现在..我需要我的菜单项具有单击事件处理程序...我该如何指定?我一直在搜索,但无法找到...我尝试获取对新菜单项的引用:



Now.. I need my menuitems to have a click event handler... how do I specify that? I have been searching but I am unable to find out... I tried getting a reference to the new menu item:

Dim x As Integer
Dim mi As MenuItem
...
If IsArray(sProjectList) Then
            For i = sProjectList.GetLowerBound(0) To sProjectList.GetUpperBound(0)
                x = miProjectList.Items.Add(sProjectList(i, 0).ToString)
                mi = DirectCast(miProjectList.Items(x), MenuItem)
                '''what to do now???
            Next i
        End If




我敢肯定这很容易,但是我只是停留在这一步上.预先感谢您的帮助!




I am sure this is very easy, but I am just stuck on this one. Thank you in advance for your help!

推荐答案

您需要将事件附加到Menuitem
Menuitem + = new(对应的事件处理程序)(methodName)
You Need to attach the event to the Menuitem
Menuitem+=new (Corresponding event Handler)(methodName)


这是实现该功能的VB.NET代码(带有问题的代码将在投射到菜单项时给出运行时错误):

This is the VB.NET code that does the trick (the one posted with the question would give a runtime error when casting to menu item):

Dim sProjectList(,) As Object 'array with project names and ids
Dim mi As MenuItem
...
If IsArray(sProjectList) Then
    For i = sProjectList.GetLowerBound(0) To sProjectList.GetUpperBound(0)
        mi = New MenuItem()
        mi.Header = sProjectList(i, 0).ToString
        AddHandler mi.Click, AddressOf subShowOneProject
        miProjectList.Items.Add(mi)
    Next i
End If



miProjectList是我在xaml文件中定义的菜单项.
subShowOneProject是处理click事件的过程.

HTH,

虹膜



miProjectList is a menuitem I defined in the xaml file.
subShowOneProject is the procedure that handles the click event.

HTH,

Iris


这篇关于在rutime添加WPF菜单项-如何指定单击事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆