首页 > 解决方案 > WPF:如何从不同的页面绑定我的集合

问题描述

所以我的Collection里面有这个ViewModel

public class ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private ObservableCollection<NetworkInterface> _interfaces;

        public ViewModel()
        {
            Interfaces = NetworkInterface.ReadAll();
        }

        public ObservableCollection<NetworkInterface> Interfaces
        {
            get { return _interfaces; }
            set
            {
                _interfaces = value;
                NotifyPropertyChanged();
            }
        }

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

NetworkInterface是实现PropertyChanged的,当应用程序开始使用项目时。

初始化我的ViewMode

public MainWindow()
{
     InitializeComponent();
     viewModel = new ViewModel();
 }

我的应用程序中有另一个在按钮之后Page加载:FrameClick

<Grid Name="GridMain" Grid.Row="1">
          <Frame Name="MyFrame"
                 NavigationUIVisibility="Hidden"
                 Source="Pages/home.xaml"/>
</Grid>

加载Page

Home home = new Home();
MyFrame.Content = home;

在我的里面ComboBox

<ComboBox ItemsSource="{Binding Interfaces}" Height="30" Width="300"/>

我也尝试:

<ComboBox ItemsSource="{Binding Path=Interfaces}" Height="30" Width="300"/>

但我ComboBox的还是空的

编辑

如果这ComboBox是在主应用程序内部而不是在它内部,Page则可以正常工作。

标签: wpfdata-bindingbindingpropertychanged

解决方案


的不是中的。DataContext_ 您可以通过编程方式设置 Frame 的 DataContext:MainWindowDataContextPageFrame

PageinFrame不会自动从 继承,DataContext但是您可以在加载 时MainWindow设置其属性:DataContextPage

Home home = new Home();
home.DataContext = viewModel;
MyFrame.Content = home;

推荐阅读