Reputation: 455
I have one observable collection binds to combo box.
Below is the Xaml
<ComboBox Name="Combo" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding Path=coll}"/>
<Button Content="Button" Click="Button_Click_1" HorizontalAlignment="Left" VerticalAlignment="Top"
Width="75" RenderTransformOrigin="0.649,3.417" Margin="10,36,0,0"/>
Below is my code
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public ObservableCollection<string> _coll { get; set; }
public ObservableCollection<string> coll
{
get
{
return _coll;
}
set
{
_coll = value;
PropertyChanged(this, new PropertyChangedEventArgs("coll"));
}
}
public MainWindow()
{
InitializeComponent();
coll = new ObservableCollection<string>();
coll.Add("ABC");
coll.Add("AAA");
coll.Add("BBB");
coll.Add("KKK");
Combo.SelectedItem = coll[0];
DataContext = this;
}
public MainWindow(string data)
: this()
{
coll.Add(data);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Window1 window = new Window1();
window.Show();
}
}
Now I am opening new window on button click event and I am passing the data from the second window to Mainwindow in this case binding is not working
Second window Xaml
<TextBox Name="txtBox" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap"
VerticalAlignment="Top" Width="120"/>
<Button Content="Button" Click="Button_Click_1" HorizontalAlignment="Left"
VerticalAlignment="Top" Width="75" Margin="10,28,0,0"/>
Code
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
MainWindow obj = new MainWindow(txtBox.Text);
this.Close();
}
}
Upvotes: 2
Views: 974
Reputation: 783
In your main window you have to add observable collection to other Constructor, Otherwise Observable Collection has no data.
public MainWindow(string data)
: this()
{
coll = new ObservableCollection<string>();
coll.Add("ABC");
coll.Add("AAA");
coll.Add("BBB");
coll.Add("KKK");
Combo.SelectedItem = coll[0];
DataContext = this;
coll.Add(data);
}
this works if you create another instance of the mainwindow.
Upvotes: 1