繁体   English   中英

在页面的主窗口中为按钮添加了事件处理程序,该按钮不起作用

[英]Added event handler in Main Window for the Button, which is in the Page does not work

我将WPF用于我的非常简单的项目。 我已经使用Page类创建了登录页面,并且那里有两个控件。 它们是Button和TextBox。 然后我通过框架在主窗口中使用此页面。 在主窗口中,我试图将事件处理程序添加到“单击”事件的“按钮”上,为什么它不起作用。 没有错误消息或其他东西。 我尝试调试,但是它没有输入方法。

这是页面代码:

<Page x:Class="BJack.LoginPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    Title="LoginPage">

    <Page.Resources>
        <Style TargetType="TextBox" x:Key="txtHint">
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocused" Value="False">
                    <Setter Property="Text" Value="Login" />
                    <Setter Property="Foreground" Value="#FFB8A8A8" />
                </Trigger>
            </Style.Triggers>
            <Style.Setters>
                <Setter Property="Height" Value="25" />
                <Setter Property="FontSize" Value="16" />
                <Setter Property="Width" Value="300" />
            </Style.Setters>
        </Style>
    </Page.Resources>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

        <StackPanel VerticalAlignment="Center">
            <TextBox Name="txtLogin" Style="{StaticResource ResourceKey=txtHint}"></TextBox>
            <Button Grid.Row="1" Height="30" Width="150" Margin="0 30 0 0" Name="enterButton">Enter</Button>
        </StackPanel>

    </Grid>
</Page>

这是一个MainWindow代码:

public partial class MainWindow : Window
{
    LoginPage lPage = new LoginPage();

    public MainWindow()
    {
        InitializeComponent();
        InitializeProgramm();
    }

    private void InitializeProgramm()
    {
        mainFrame.NavigationService.Navigate(new Uri("LoginPage.xaml", UriKind.Relative));
        lPage.enterButton.Click += enterButton_Click;
    }

    void enterButton_Click(object sender, RoutedEventArgs e)
    {
        if (lPage.txtLogin.Text.Length > 0)
        {
            mainFrame.Navigate(new Uri("GamePage.xaml", UriKind.Relative));
            this.WindowState = System.Windows.WindowState.Maximized;
        }
    }

    private void mainWin_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Keyboard.ClearFocus();
    }
}

这是一个解决方案

private void InitializeProgramm()
{
    mainFrame.NavigationService.Navigate(lPage);
    lPage.enterButton.Click += enterButton_Click;
}

这会将实例lPage设置为附加了事件处理程序的mainFrame的内容,而不是新创建的实例

暂无
暂无

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

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