问题是您没有访问MainWindow
CbservableCollection,您正在创建一个新的MainWindow
.
如果这Window1
是一个对话框,您有几个选项
- 将 MainWindow 作为其所有者传递给 Window1
- 将 Window1 用作对话框并在关闭时获取更改
我个人认为第二个选项是最好的,但这取决于你如何打电话Window1
示例 2:
主窗口类
public partial class MainWindow : Window
{
private ObservableCollection<User> _myList = new ObservableCollection<User>();
public MainWindow()
{
InitializeComponent();
}
public ObservableCollection<User> MyCollection
{
get { return _myList; }
set { _myList = value; }
}
private void button1_Click_1(object sender, RoutedEventArgs e)
{
var dialog = new Window1();
if (dialog.ShowDialog() == true)
{
MyCollection.Add(dialog.NewUser);
}
}
}
主窗口xml
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="233" Width="405" Name="UI">
<Grid DataContext="{Binding ElementName=UI}" >
<ListBox ItemsSource="{Binding MyCollection}" DisplayMemberPath="TextA" Margin="0,0,0,47" />
<Button Content="Add" Height="23" HorizontalAlignment="Left" Margin="0,0,0,12" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click_1" />
</Grid>
</Window>
Window1 xaml
<Window x:Class="WpfApplication8.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="119" Width="300" Name="UI">
<StackPanel DataContext="{Binding ElementName=UI}">
<TextBox Text="{Binding NewUser.TextA}" />
<TextBox Text="{Binding NewUser.TextB}" />
<Button Click="button1_Click" HorizontalAlignment="Right" Width="90" Height="30" Content="Add" />
</StackPanel>
</Window>
Window1 代码
public partial class Window1 : Window, INotifyPropertyChanged
{
private User _newUser = new User();
public Window1()
{
InitializeComponent();
}
public User NewUser
{
get { return _newUser; }
set { _newUser = value; NotifyPropertyChanged("NewUser"); }
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
用户类
public class User : INotifyPropertyChanged
{
private string _textA;
private string _textB;
public string TextA
{
get { return _textA; }
set { _textA = value; NotifyPropertyChanged("TextA"); }
}
public string TextB
{
get { return _textB; }
set { _textB = value; NotifyPropertyChanged("TextB"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}