Event Handler located in different class than MainWindow

不羁岁月 提交于 2019-12-10 14:12:25

问题


So I followed the guide on the following site to restrict the characters a textbox can accept.

http://www.rhyous.com/2010/06/18/how-to-limit-or-prevent-characters-in-a-textbox-in-csharp/

My problem is I can't figure out how to make the event handler trigger in the secondary class. Basically how do I tell VS to look for the event handler code in that class instead of MainWindow? I tried searching, but apparently don't know the correct terms to use. The xaml reference I used was

xmlns:DigitBox="clr-namespace:System.Windows.Controls;assembly=PresentationFramework"

Any ideas?


回答1:


You are much better off using commands and command bindings. I'm not sure what the specific command that would would bind to for a text box for your desired functionality, but one of the goals for WPF was to lessen the use of Event Handlers in code behind.

Check out this article for an overview of commands and this article for a way to hook up commands with events. WPF commanding is one of the coolest features to enable true separation of concerns between UI and business logic.

As a worst case scenario solution, you could create your own text box that inherits from the text box control and hook up the events in that class. Your control would then be reusable.




回答2:


Simplest way I've found to do it is assign the event in your constructor.

public MainWindow()
    {
        InitializeComponent();
        TextBoxCurrency.GotFocus += expandedTextBoxEvents.TextBoxCurrencyGotFocus;
        TextBoxCurrency.LostFocus += expandedTextBoxEvents.TextBoxCurrencyLostFocus;
    }

I've searched a way to do it in XAML and I did not found an easy and clean way to do it.



来源:https://stackoverflow.com/questions/8021590/event-handler-located-in-different-class-than-mainwindow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!