c# - 将 WPF 组合框 itemssource 绑定到另一个 .cs 文件中的属性
问题描述
我正在尝试将组合框绑定到我在另一个文件中定义的属性。
组合框,位于OptionsWindow.xaml
:
<ComboBox x:Name="InputDevicesComboBox"
VerticalAlignment="Top"
Text="Please Select Input Device"
ItemsSource="{Binding InputDeviceNames, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type SIPBandVoIPClient:MainWindow}}}"/>
该物业,位于MainWindow.xaml.cs
:
private List<string> _inputDeviceNames;
public List<string> InputDeviceNames
{
get => _inputDeviceNames;
private set
{
_inputDeviceNames = value;
OnPropertyChanged("InputDeviceNames");
}
}
打开选项窗口时的错误:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='SIPBandVoIPClient.MainWindow', AncestorLevel='1''. BindingExpression:Path=InputDeviceNames; DataItem=null; target element is 'ComboBox' (Name='InputDevicesComboBox'); target property is 'ItemsSource' (type 'IEnumerable')
我认识到对此有很多问题,但我并不太了解 WPF 绑定,似乎无法让它们工作......
我使用 Visual Studio 中的内置绑定创建创建了这个绑定,所以我认为它会起作用。经过一番搜索,我认为问题在于该属性位于不同的文件中,或者它不是可视树的一部分(?)。
我确实有一个与 MainWindow.xaml.cs 中定义的属性的绑定,并且绑定在 MainWindow.xaml 中运行良好,因此我认为这是由于位于不同的文件中。
谢谢您的帮助。
解决方案
您可以创建一个视图模型对象来在这两个窗口之间交换数据,并将其传递给两个窗口实例的 DataContext。然后你不需要绑定属性中的任何相对源,而只是在路径中设置属性的名称,包含你的列表。或者更好地查看 MVVM 设计模式 https://blogs.msdn.microsoft.com/msgulfcommunity/2013/03/13/understanding-the-basics-of-mvvm-design-pattern/
创建一个视图模型类 mainViewModel.cs:
class MainViewModel {
List<string> InputDeviceNames { get; private set; }
public MainViewModel() {
InputDeviceNames = new List<string>();
}
}
然后在 MainWindow.xaml.cs 类中使用它:
private MainViewModel _viewModel;
public MainWindow() {
_viewModel = new MainViewModel();
DataContext = _viewModel;
// anywhere in code you can use your _viewModel to exchange data
}
public OpenOptionsWindowCode() {
var options = new OptionsWindow();
options.DataContext = _viewModel;
options.Show();
}
在您的 OptionsWindow.xaml 中:
<ComboBox x:Name="InputDevicesComboBox"
VerticalAlignment="Top"
Text="Please Select Input Device"
ItemsSource="{Binding InputDeviceNames}"/>
如果您在 MainWindow.xaml 中的绑定中使用 InputDeviceNames,请务必通知视图有关项目的更改。然后使用ObservableCollection<T>
而不是List<T>
. 如果您将扩展您的视图模型以保存其他值,请INotifyPropertyChanged
在 MainViewModel 类上实现接口。
MVVM 是一种强大的 UI 开发模式,因此经过一些努力学习它,您会以更少的努力获得更好的结果。
希望它可以帮助你。
推荐阅读
- html - HTML/CSS - 文本不能在按钮内居中
- python - ldap3.MODIFY_REPLACE 单引号 ( ' )
- javascript - 从数组中删除唯一的随机项目,然后重新填充以重新启动该过程?
- count - 计数(时间戳)返回 0 DB2
- sql - TABLEAU 计算字段优化
- c# - 下拉不显示值和文本 asp.net mvc
- python - 在 Apache Cassandra 中混合执行两个 Python 脚本和 DatastaxBulk 加载器脚本以加载到 .csv
- reactjs - api接收到的数据中的ReactJs .map
- node.js - 使用 sequelize 查询 Postgres 嵌套 JSONB 列
- php - 将 JSON 从 MySQL 转换为 PHP