创建新窗口时的数据上下文问题

本文关键字:数据 上下文 问题 新窗口 窗口 创建 | 更新日期: 2023-09-27 18:06:00

我有一个问题,我相信这很容易解决,但我就是不能得到我的数据上下文正确。

我有一个弹出窗口的组合框(cmbChannel)。当您关闭弹出窗口时,将打开主窗口,并在txtChannel中显示从该组合框中选择的值的标签。

在弹出窗口(点击按钮可以随时弹出),我检查主窗口是否打开,然后我打开它或什么都不做: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

我确保设置了我的主窗口的DataContext。

这是我的弹出式组合框:
<ComboBox x:Name="cmbChannel" ItemsSource="{Binding CmbContent}" SelectedItem="1" HorizontalAlignment="Left" Margin="94,127,0,0" VerticalAlignment="Top" Width="91"/>很简单。

现在,在我的主窗口中,我认为我所要做的就是:

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

但这不起作用。我很确定这是数据上下文问题,也许我没有正确声明?不确定。任何帮助都是感激的!

创建新窗口时的数据上下文问题

是的,我一开始就错了。

我想,当你关闭popup,它的所有元素都被处理掉了。我建议你将cmbChannel的SelectedValue绑定到Popup DataContext,然后做我之前写的:

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

它的ViewModel(示例):

public class PopupViewModel
{
    public ObservableCollection<YourItemClass> CmbContent { get; set; }
    public YourItemClass SelectedEntry { get; set; }
    // Implement INotifyPropertyChanged if needed also
}

然后:

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