WPF新窗口及内容

4

我想在现有的主窗口旁边创建一个带有可滚动文本框的新窗口。

我在主窗口上按下“打开新窗口”按钮,然后它应该打开一个带有可滚动文本框的新窗口。

form2

在WPF中,您可以将元素拖放到主窗口中,但无法对新窗口执行此操作。因此,我认为只有在MainWindow.xaml.cs中创建新窗口时才可能实现。

我能够通过以下方式创建新窗口:

private void btnConnect_Click(object sender, RoutedEventArgs 
 {
    Form form2 = new Form();
    //Do intergreate TextBox with scrollbar in form2

    form2.Show();

 }

现在我想要一个文本框。

但是我该如何在C#或WPF中实现它?

谢谢。


在VS中创建表单,就像您使用主表单一样。然后使用您的代码片段打开并显示该表单。 - TheGeekZn
2
你确定你在询问的是WPF窗口而不是WinForms窗口吗? - Andrei Zubov
@AndreiZubov:我猜测,但是点击处理程序具有RoutedEventArgs参数,表明它是WPF事件处理程序。然而,form2可能是一个System.Windows.Forms.Form,这表明Windows Forms可能被错误地混合到应用程序中。 - Martin Liversage
2个回答

9

好的,您可以创建一个新窗口并将一个在新XAML中创建的UserControl加载到该窗口的Windows.Content中。示例:

NewXamlUserControl ui = new NewXamlUserControl();
MainWindow newWindow = new MainWindow();
newWindow.Content = ui;
newWindow.Show();

Xaml可以像这样:

<UserControl x:Class="Projekt"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       x:Name="newXamlUserControl"      
        Height="300" Width="300">

    <Grid>

        <TextBox Text = ..../>

    </Grid>
</UserControl>

8

在您的项目中创建一个新的WPF窗口:

  1. Project -> Add New Item -> Window (WPF)
  2. Name the window appropriately (here I use ConnectWindow.xaml)
  3. Add a TextBox to the XAML

    <Window
        x:Class="WpfApplication1.ConnectWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Connect"
        Height="300"
        Width="300"
        ShowInTaskbar="False">
        <TextBox
            AcceptsReturn="True"
            VerticalScrollBarVisibility="Auto"
            HorizontalScrollBarVisibility="Auto"/>
    </Window>
    

    You can customize both Window and TextBox as you like.

有几种方法可以显示窗口。

显示模态窗口(this指主窗口):

var window = new ConnectWindow { Owner = this };
window.ShowDialog();
// Execution only continues here after the window is closed.

显示一个非模态子窗口:

var window = new ConnectWindow { Owner = this };
window.Show();

显示另一个顶级窗口:

var window = new ConnectWindow();
window.Show();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接