简体   繁体   English

WPF-如何从类外部将事件处理程序添加到元素?

[英]WPF - How to add event handler to element from outside the class?

I am searching for answer many hours and with no success. 我正在寻找答案很多小时,但没有成功。 There is the way to do that, but every included element has to be static. 有办法做到这一点,但是每个包含的元素必须是静态的。 What is not suitable for me. 什么不适合我。

I have MainPage class and Tile class. 我有MainPage类和Tile类。 This tile class instantiates few kinds of tiles in MainPage layout. 此图块类实例化MainPage布局中的几种图块。 I need to add to some kinds of these tiles Tapped event. 我需要添加某些类型的Tapped事件。 This event should modify MainPage elements. 此事件应修改MainPage元素。

What is the best way to do that? 最好的方法是什么? I always end with "non-static warning", as you can see in the code: 如代码所示,我总是以“非静态警告”结尾:

public class Tile
{
   public static Grid buttonTile_MapPanel(int rowNum, int colNum)
    {
        Grid mapPanelButton = new Grid();
        mapPanelButton.Background = new SolidColorBrush(Color.FromArgb(255, 50, 50, 50));
        TextBlock title = new TextBlock();
        title.Text = "Mapa";
        title.HorizontalAlignment = HorizontalAlignment.Center;
        title.VerticalAlignment = VerticalAlignment.Center;
        title.Foreground = new SolidColorBrush(Colors.White);
        mapPanelButton.Children.Add(title);

        //this will be signed as error: An object reference is required for non static field...
        mapPanelButton.Tapped += new RoutedEventHandler(MainPage.mapPanelService);

        return mapPanelButton;
    }
}

public sealed partial class MainPage : Page
{
    public void mapPanelService(object sender, RoutedEventArgs e) 
    {
        MapPanel.Margin = new Thickness(0,0,0,0);
    }  
}

Main problem was bad type of handler, which demanded something else than it should. 主要问题是处理程序的类型错误,它要求的东西超出了应有的范围。

Correct code: public void dataPanelService(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { . 正确的代码:public void dataPanelService(object sender,Windows.UI.Xaml.Input.TappedRoutedEventArgs e){。 . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM