【问题标题】:c# WPF button link to user control pagec# WPF按钮链接到用户控制页面
【发布时间】:2013-07-03 00:51:54
【问题描述】:

我有一个只有一个按钮的 MainWindow,如何将此按钮链接到用户控制页面 (home.xaml)?我是 WPF 新手 在我的主窗口中:

<Button Height="100" Name="btnHome" Width="103" Click="btnHome_Click"/>

在我的 mainwindow.cs 中:

    private void btnHome_Click(object sender, RoutedEventArgs e)
    {
        var home = new home();
        home.Show();
    }

但它不起作用。 home.xaml 是我想通过单击主窗口中的按钮链接到的用户控制页面。

【问题讨论】:

    标签: c# wpf button user-controls


    【解决方案1】:
     <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <br />
     <asp:Button ID="Button1" runat="server" Text="Next" onclick="Button1_Click" />
    Page1.aspx.cs
    
    protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Session["Name"] != null)
                    txtName.Text = Session["Name"].ToString();
            }
        }
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            Session["Name"] = txtName.Text;
            Response.Redirect("Page2.aspx");
        }
    Page2.aspx
    
    <asp:Button ID="Button1" runat="server" Text="Back" onclick="Button1_Click" />
    Page2.aspx.cs
    
     protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Page1.aspx");
        }
    

    【讨论】:

    • 不确定将 ASP.NET 引入 WPF 是否能解决问题 :)
    【解决方案2】:

    您应该能够使用 NavigationService 在 WPF 页面之间导航

    例子:

    private void btnHome_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.GetNavigationService(this).Navigate("home.xaml");
    }
    

    【讨论】:

    • 您好,感谢您的回复,但有一个错误提示没有 NavigationService 的定义,我尝试:使用 System.Windows.Navigation.NavigationService;但错误仍然存​​在
    【解决方案3】:
    Window w = new Window();
    w.Content = new UserControl1();
    w.Show();
    

    【讨论】:

      【解决方案4】:

      在按钮上使用此代码并在 uri 中设置您的用户控件名称或路径。

      private void btn_Click(object sender, RoutedEventArgs e)
      {
          NavigationService.GetNavigationService(this)
             .Navigate(new Uri("/UserControls/GameDetails.xaml", UriKind.RelativeOrAbsolute));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-01
        • 2012-11-18
        • 1970-01-01
        • 2014-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多