我是WPF和C#的新手。我知道很多VB.NET,我习惯于调用表单对象,例如文本框等。我从另一个表单中进行调用。现在,我正在使用WPF,我感到困惑。因为我有一个主窗口。而我想从一个类中向主窗口的列表框中添加项目。在VB.Net中,就像这样。
IN FORM2
Form1.Textbox.Text = "";
我无法在WPF中完成这个任务。请有人帮忙。谢谢!
我是WPF和C#的新手。我知道很多VB.NET,我习惯于调用表单对象,例如文本框等。我从另一个表单中进行调用。现在,我正在使用WPF,我感到困惑。因为我有一个主窗口。而我想从一个类中向主窗口的列表框中添加项目。在VB.Net中,就像这样。
IN FORM2
Form1.Textbox.Text = "";
我无法在WPF中完成这个任务。请有人帮忙。谢谢!
// MainWindow
<Window x:Class="TestApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox Name="mainListBox" Height="250" HorizontalAlignment="Stretch" VerticalAlignment="Top"/>
<Button Content="Open Another Window" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="20" Click="OpenAnotherWindow_Click"/>
</Grid>
</Window>
and
// AnotherWindow
<Window x:Class="TestApplication.AnotherWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AnotherWindow" Height="300" Width="300">
<Grid>
<Button Content="Add New Item to Main Window" HorizontalAlignment="Center" VerticalAlignment="Center" Click="AddNewItem_Click"/>
</Grid>
</Window>
private void OpenAnotherWindow_Click(object sender, RoutedEventArgs e)
{
AnotherWindow anotherWindow = new AnotherWindow();
anotherWindow.Owner = this;
anotherWindow.ShowDialog();
}
private void AddNewItem_Click(object sender, RoutedEventArgs e)
{
MainWindow mainWindow = Owner as MainWindow;
mainWindow.mainListBox.Items.Add(new Random().Next(1000).ToString());
}
ListBox
添加一个新的随机数,以展示代码如何访问和修改MainWindow
中控件的数据。这将获取所有活动窗口:
foreach (Window item in Application.Current.Windows)
{
}
纯WPF解决方案,但在您的情况下可能是最简单的方法,是使用WPF中的数据绑定。
每个表单控件都绑定到ModelView上的某些数据(纯MVVM方法)或数据(更多或更少像您可以在WindowsForms中做的那样)。因此,“唯一”的事情是读取/写入绑定到该表单UI上的控件的数据。
例如,您在Windows上有一个TextBox
并希望从中读取数据。这个TextBox
绑定到负责保存该表单上控件数据的类的某个string
属性(仅为示例,在实际世界中可能有1000种其他解决方案,基于开发人员的决策)。因此,您需要的不是说:“窗口给文本框”,然后读取TextBox
的内容,而是简单地读取绑定的string
属性。
这只是一件东西的简单描述。但是只是为了给你一个提示。请按照上面提供的数据绑定链接了解更多关于这个东西的信息。不要害怕那里有很多东西,毕竟这不是一个复杂的想法,而且也相当直观。在简单情况下使这个东西工作,你不需要像我一样付出巨大的努力。当你进入实际应用时,这个东西会变得非常复杂。