首页 > 解决方案 > 将 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 中运行良好,因此我认为这是由于位于不同的文件中。

谢谢您的帮助。

标签: c#wpfxamldata-binding

解决方案


您可以创建一个视图模型对象来在这两个窗口之间交换数据,并将其传递给两个窗口实例的 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 开发模式,因此经过一些努力学习它,您会以更少的努力获得更好的结果。

希望它可以帮助你。


推荐阅读