首页 > 解决方案 > 在已经绑定的 ListView 中显示来自数据库的列表

问题描述

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

看法

<ListView ItemsSource="{Binding myModel.myCollection}" Grid.Row="1" Grid.Column="0">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Name, Mode=TwoWay}"></TextBox>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>

                    <GridViewColumn Header="Category Tag">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox ItemsSource="{Binding myModel.CategoryList}"></ComboBox>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

模型

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));
        }
    }
}

为简单起见,我排除了 ViewModel 和 Code-Behind,但在InitialiseComponent()之后,我有DataContext = new TestViewModel()并且在我的 ViewModel 中,我有一个属性,它创建了我的模型的新实例,并添加了一个 getter 以确保一切正常无障碍。请放心,列表会被填充我只是想单独填充一个下拉列表。

标签: c#wpfxaml

解决方案


发生这种情况是因为,组合框的数据上下文将是 myModel 的项目。
您需要明确告诉组合框从它的父数据上下文中获取 itemssource。

<DataTemplate>
     <ComboBox ItemsSource="{Binding DataContext.myModel.CategoryList, RelativeSource={RelativeSource AncestorType=DataGrid}}"></ComboBox>
</DataTemplate>

推荐阅读