wpf - 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
加载:Frame
Click
<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
则可以正常工作。
解决方案
的不是中的。DataContext
_ 您可以通过编程方式设置 Frame 的 DataContext:MainWindow
DataContext
Page
Frame
Page
inFrame
不会自动从 继承,DataContext
但是您可以在加载 时MainWindow
设置其属性:DataContext
Page
Home home = new Home();
home.DataContext = viewModel;
MyFrame.Content = home;
推荐阅读
- google-cloud-platform - 具有单一 cloudbuild 的 Mono-repository 架构中的 Google Cloud Build 管道
- json - 如何在 Powershell 中扩展 JSON 字符串中的变量?
- java - 通过公共键值比较两个 Json 对象 - java 方法
- postgresql - 在 ubuntu 18.04 中安装 GDAL 后 postgis 无法正常工作
- swift - UIScrollView 约束意外行为
- ios - iOS 上的 Webview 渲染问题 [Testflight]
- laravel - 一般错误:1005 无法创建表 `chatbot`.`staistic_students`(错误号:150“外键约束格式不正确”)
- python - 错误:network_service_instance_impl.cc(262)] 网络服务崩溃,重新启动服务。python 仅编译为可执行文件时出现 Pyqt5 错误。视窗
- java - 使用 th:object 保存所有对象
- arduino - ESP8266-01 如何使用电阻将 GPIO 接地,如下图所示