C# 在ListView中显示已绑定的数据库中的列表

C# 在ListView中显示已绑定的数据库中的列表,c#,wpf,xaml,C#,Wpf,Xaml,澄清正在发生的事情。基本上我有一个ListView绑定,它指向对象中的列表。在同一个对象中,但不在列表中,我有另一个列表,其中包含用于下拉列表的字符串,我无法将其分配给列表视图,因为DataContext已设置为提到的第一个列表。有人能提供一个解决方案,或者更好的更有效的方法来处理这个问题吗 看法 模型 为简单起见,我排除了ViewModel和代码隐藏,但在InitialiseComponent之后,我有DataContext=new TestViewModel,在我的ViewModel中,我有

澄清正在发生的事情。基本上我有一个ListView绑定,它指向对象中的列表。在同一个对象中,但不在列表中,我有另一个列表,其中包含用于下拉列表的字符串,我无法将其分配给列表视图,因为DataContext已设置为提到的第一个列表。有人能提供一个解决方案,或者更好的更有效的方法来处理这个问题吗

看法 模型


为简单起见,我排除了ViewModel和代码隐藏,但在InitialiseComponent之后,我有DataContext=new TestViewModel,在我的ViewModel中,我有一个属性,它创建了我的模型的一个新实例,并添加了一个getter,以确保所有内容都是可访问的。请放心,列表会被填充,我只是想分别填充一个下拉列表。

之所以发生这种情况,是因为组合框的datacontext将是myModel的项。 您需要显式地告诉组合框从其父对象的datacontext获取itemssource

<DataTemplate>
     <ComboBox ItemsSource="{Binding DataContext.myModel.CategoryList, RelativeSource={RelativeSource AncestorType=DataGrid}}"></ComboBox>
</DataTemplate>
public class SiteUrlsModel : INotifyPropertyChanged
    {
        public string CaseName { get; set; }
        public List<string> TestList => new List<string> { "Test1", "Test2", "Test3" };

        public List<string> _categoryTagList;
        public List<string> CategoryTagList
        {
            get => _categoryTagList;
            set
            {
                if (_categoryTagList == value)
                    return;
                _categoryTagList = value;
                OnPropertyChanged();
            }
        }

        private ObservableCollection<SiteUrlsModel> _myCollection;
        public ObservableCollection<SiteUrlsModel> myCollection
        {
            get => _siteurlscCollection;
            set
            {
                if (_siteurlscCollection == value)
                    return;
                _siteurlscCollection = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
<DataTemplate>
     <ComboBox ItemsSource="{Binding DataContext.myModel.CategoryList, RelativeSource={RelativeSource AncestorType=DataGrid}}"></ComboBox>
</DataTemplate>