将实例化的属性传递给第二个WPF窗口,然后在OK时返回属性
本文关键字:属性 然后 OK 窗口 返回 第二个 实例化 WPF | 更新日期: 2023-09-27 18:16:52
当用户双击窗口1中的listview项时,会弹出第二个窗口。
我想将listview项的实例传递给第二个窗口,它将用于填充GUI中的数据。当第二个窗口关闭时,它应该返回来自GUI的新值。为什么这似乎不起作用?
"双击"出错。它不允许我直接设置属性CurrentItem = selUser。我得到这个错误:
错误1 'System.Windows。Window'不包含'CurrentItem'的定义,也没有扩展方法'CurrentItem'接受类型为'System.Windows '的第一个参数。可以找到窗口(您是否缺少using指令或汇编引用?)C:'Users'jmartini'Projects'wpf_listShowSelected'WpfApplication1_setup01'WpfApplication1'MainWindow.xaml.cs 34 24 WpfApplication1
此外,我不能得到的值返回使用User val = editDialog。当对话框返回OK时,CurrentItem。我得到了与上面提到的相同的错误。
我不清楚如何解决这个问题。
WPF窗口1 (CS):
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<User> items = new List<User>();
items.Add(new User() { Name = "John Doe", Age = 42, Mail = "john@doe-family.com", Info = "A basketball player" });
items.Add(new User() { Name = "Jane Doe", Age = 39, Mail = "jane@doe-family.com", Info = "A soccer player" });
items.Add(new User() { Name = "Sammy Doe", Age = 13, Mail = "sammy.doe@gmail.com", Info = "A hockey player" });
lvDataBinding.ItemsSource = items;
}
private void listViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListViewItem item = sender as ListViewItem;
// create instance of original User to use for second window
User selUser = item.Content as User;
// POPUP WINDOW
Window editDialog = new EditWindow();
editDialog.Owner = this;
editDialog.CurrentItem = selUser;
editDialog.ShowDialog();
if (editDialog.DialogResult.HasValue && editDialog.DialogResult.Value)
{
User val = editDialog.CurrentItem;
Console.WriteLine("User pressed OK");
}
else
{
Console.WriteLine("User pressed Cancel");
}
}
}
}
WPF Window 2 (CS):
using System.Windows;
namespace WpfApplication1
{
public partial class EditWindow : Window
{
public User CurrentItem {get; set;}
public EditWindow()
{
InitializeComponent();
}
private void ButtonOkClick(object sender, RoutedEventArgs e)
{
DialogResult = true;
Close();
}
private void ButtonCancelClick(object sender, RoutedEventArgs e)
{
DialogResult = false;
Close();
}
}
}
更改为EditWindow;