如何使用C#在WPF中获取MenuItem标头 [英] How to get MenuItem Header in WPF using C#

查看:68
本文介绍了如何使用C#在WPF中获取MenuItem标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

item2.AddHandler(MenuItem.ClicEvent,新的RoutedEventHandler(item2_Click))


公共无效item2_Click(对象发送者,RoutedEventArgs e)
{

MenuItem val =(MenuItem)sender;

//这里我要获取item2标头
在下一行显示错误
字符串str = val.Header; ///错误此行

}

item2.AddHandler(MenuItem.ClicEvent, new RoutedEventHandler(item2_Click))


public void item2_Click(object sender, RoutedEventArgs e)
{

MenuItem val=(MenuItem)sender;

//here i want to get item2 header
shows an error the following line
string str=val.Header; /// error this line

}

推荐答案

属性System.Windows.Controls.MenuItem.HeaderSystem.Object,而不是string.在某些或所有情况下,标头的实际运行时类型可能是字符串,但是编译器知道吗?

请参阅 http://msdn.microsoft.com/en-us/library/system .windows.controls.menuitem.aspx [ ^ ].

如果要使用字符串,则需要动态类型转换:

The property System.Windows.Controls.MenuItem.Header is System.Object, not string. Your actual runtime type of the header might be string in some or all cases, but the compiler knows?

See http://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.aspx[^].

If you want to work with string, you need a dynamic type cast:

string stringHeader = val.Header as string;
if (stringHeader != null) // is true only if (val.Header != null) & (val.Header is string)
   //...



但是,这不是一种完美的OOP样式.理想情况下,您不需要字符串,但应该有一个功能对象,该对象可以执行您想要的语义并从其ToString方法返回正确的UI友好字符串.

这是另一种方式.它对某些对象有意义,而对另一些对象则没有意义.这不是问题,因为您需要正确设计用作标题的对象.因此,请尝试以下操作:



This is not a perfect OOP style though. Ideally you should not need a string, but you should have a functional object which does what you want semantically and returns proper UI-friendly string from its ToString method.

Here is another way. It makes sense for some objects and no sense for others. This is not a problem, as you need to design your objects used as a header properly. So, try this:

if (val.Header != null)
    string str = val.Header.ToString();
//...



再次,这不是完美的.理想情况下,您根本不应该依赖此字符串.这是很有可能的,但是您需要正确设计UI.

—SA



Again, this is not perfect. Ideally you should not rely on this string at all; this is quite possible, but you need to design the UI properly.

—SA


val.Header是一个对象,您不能简单地将其分配给字符串变量.您必须先将其解析为字符串,然后再将其分配给字符串变量.请尝试以下代码
val.Header is an object you can not assign it to string variable simply. You have to parse it to string before assigning it to string variable. Please try below code
string str = val.Header as string;


希望我能正确理解您的问题,我的回答对您有所帮助.


Hope I understood your question correctly and my answer helped you.


这篇关于如何使用C#在WPF中获取MenuItem标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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