WPF应用程序中的全局变量 [英] global variable in WPF application

查看:511
本文介绍了WPF应用程序中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!!



我正在使用WPF应用程序。这个应用程序包含两个项目(MainProject和UserControlProject)。



我想实现以下目标。



在UserControlProject我有一个包含TextBox的控件。每次此TextBox获得焦点时,屏幕上都会显示一个键盘。我想在MainProject窗口上的Combobox上启用/禁用此键盘。



如何实现它?



我一直在寻找全局变量等解决方案。我是在正确的方式吗?



谢谢大家。

Hi!!

I´m working on a WPF application. This app contains two projects(MainProject and UserControlProject).

I would want to achieve the following.

At UserControlProject I´ve a control that contains a TextBox. Each time this TextBox got the focus, a keyboard is shown on the screen. I´d like to enable/disable this keyboard on a Combobox included on a window from the MainProject.

How can I achieve it?

I´ve been looking for solutions like global variables. Am I on the right way?

Thanks for all.

推荐答案

在.NET中,有没有全局变量这样的概念。这是一件好事。最后!



现在,你的问题很简单,不需要任何全局的东西。您只需处理事件 System.Windows.UIElement.GotFocus System.Windows.UIElement.GotKeyboardFocus

http://msdn.microsoft.com/en -us / library / system.windows.uielement.gotfocus.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.windows.uielement.gotkeyboardfocus.aspx [ ^ ]。



假设您不想在自定义控件本身内处理它,但希望使用您的控件将其委托给任何代码。在这种情况下,您应该在控件中定义一个事件,并仍然以固定的方式处理聚焦事件,从而调用您的公共自定义事件。这样的事情:

In .NET, there is no such concept as "global variable". And this is a good thing. Finally!

Now, your problem is simple and does not require anything "global" whatsoever. You simply need to handle the event System.Windows.UIElement.GotFocus or System.Windows.UIElement.GotKeyboardFocus:
http://msdn.microsoft.com/en-us/library/system.windows.uielement.gotfocus.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.uielement.gotkeyboardfocus.aspx[^].

Suppose you don't want to handle it inside your custom control itself, but want to delegate it to whatever code using your control. In this case, you should define an event in your control and still handle the focusing event in a fixed way, invoking your public custom event. Something like this:
public class MyControl : Control {
    
    TextBox myTextBox = new TextBox();
   
    //...

    public MyControl() {
        myTextBox.GotFocus += (sender, eventArgs) => {
            if (TextBoxFocused != null)
                TextBoxFocused.Invoke(this, new System.EventArgs()); // it will call the user-supplied event handlers
        };
        //...
    }

    public event System.EventHandler TextBoxFocused; // will be invoked via the anonymous handler shown above
 
} //class MyControl





我只想提前警告你:你正在使用自己的一些虚拟键盘,它会给你以下问题:它会从文本框控件中抓取键盘焦点,所以你需要找到一种将键盘事件发送到非聚焦控件的方法,或者,通过使虚拟键盘完全不可聚焦但仍显示在顶部(存在始终在顶部样式)来防止抓取焦点。使用Forms更容易,如果这是WPF,可能会更棘手。



我描述了解决聚焦问题的想法,但它应该是一个问题一个单独的问题。首先要面对问题本身。



-SA


这篇关于WPF应用程序中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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