DataContext issue with creation of new window

时间:2015-07-31 20:21:01

标签: c# wpf

I have a problem and I'm sure it's pretty easy to sort out, but I just can't get my data context correct.

I have a popup window with a combobox (cmbChannel). When you close the popup window, the Main Window opens, with a label showing the selected value from that combobox, in txtChannel.

In the popup window (which can popup anytime with the click of a button), I check to see if the Main Window is open yet, then I either open it or do nothing: Popup.xaml.cs

//Check to see if MainWindow has been created yet
 if (App.Current.MainWindow != null && App.Current.MainWindow.GetType() == typeof(MainWindow))
 {
     this.Close();
 }
 else
 {
      //main Window hasn't been created yet so create it!
      MainWindow main = new MainWindow() { DataContext = this };
      App.Current.MainWindow = main;
      this.Close();
      main.Show();
            }
var mainwin = App.Current.Windows.OfType<MainWindow>().SingleOrDefault(w => w.IsActive);
mainwin.DataContext = this; //Set again just in case

I make sure to set the DataContext of my MainWindow.

Here's my popup combobox:
<ComboBox x:Name="cmbChannel" ItemsSource="{Binding CmbContent}" SelectedItem="1" HorizontalAlignment="Left" Margin="94,127,0,0" VerticalAlignment="Top" Width="91"/> Pretty simple.

So now, in my main window, I thought all I had to do was this:

<Label x:Name="txtChannel" Content="{Binding Path=SelectedValue, ElementName=cmbChannel}" HorizontalAlignment="Left" Margin="80,171,0,0" VerticalAlignment="Top" Width="58" />

But that isn't working. I'm pretty sure this is a data context problem, maybe I'm not declaring it correctly? Not sure. Any help is appreciated!

1 个答案:

答案 0 :(得分:0)

Yes, I was wrong at first.

I suppose, when you close popup, all its elements are disposed. I'd recommend you to bind SelectedValue of cmbChannel to Popup DataContext and then do what I wrote before:

<ComboBox x:Name="cmbChannel" 
          ItemsSource="{Binding CmbContent}" 
          SelectedItem="{Binding SelectedEntry}" />

Its ViewModel (example):

public class PopupViewModel
{
    public ObservableCollection<YourItemClass> CmbContent { get; set; }
    public YourItemClass SelectedEntry { get; set; }

    // Implement INotifyPropertyChanged if needed also
}

and then:

MainWindow main = new MainWindow() { DataContext = this.DataContext };