c# - 未在MVVM中填充组合框列表

标签 c# wpf mvvm listbox

我正在MVVM WPF中工作。我在弹出面板中包含一个listBox。显示弹出窗口,但listBox未填充,没有任何想法。list box用于过滤一列数据。这是列表框:

<ListBox x:Name="listBoxPopupContent" ItemsSource="{Binding ClassViewMethod}">
       <ListBox.ItemTemplate>
            <DataTemplate>
               <CheckBox IsChecked="{Binding IsChecked}" Content="{Binding ClassName}"/>
            </DataTemplate>
       </ListBox.ItemTemplate>
</ListBox>

和模型 View :
public ObservableCollection<ClassView> ClassViewMethod
    {
        get
        {
            foreach (string cust in ClassViewItems.Select(w => w.ClassName).Distinct().OrderBy(w => w))
            {
                classFilters.Add(new CheckedListItem<string> { Item = cust, IsChecked = true });
            }
            viewSource.Filter += viewSource_Filter;
            viewSource.Source = ClassViewItems;
            return ClassViewItems;
        }
    }

    private void viewSource_Filter(object sender, FilterEventArgs e)
    {
        ClassView cust = (ClassView)e.Item;

        int count = classFilters.Where(w => w.IsChecked).Count(w => w.Item == cust.ClassName);

        if (count == 0)
        {
            e.Accepted = false;
            return;
        }

        e.Accepted = true;
    }

    public ObservableCollection<ClassView> ClassViewItems
    {
        get
        {
            return _classView;
        }

        set
        {
            _classView = value;
            NotifyPropertyChanged("ClassViewItems");

        }

DataContext设置为(在app.xaml中):
<Application.Resources>
    <local:MainWindowViewModel x:Key="MainWindowViewModel" />
</Application.Resources>

并在MainWindow.xaml中:
 DataContext="{StaticResource MainWindowViewModel}"

最佳答案

您需要验证页面的DataContext是否已设置为VM的 Activity 实例。

其次,VM需要实现INotifyPropertyChanged来发出信号,通知存储在ClassViewMethod的项目具有更改的项目。

将目标设为ObservableCollection不会影响该动态。因此,当页面应查看集合时,会发出调用通知事件的信号,并且控件会加载数据。我在您的示例中没有看到该通知事件,因此没有两个可能的故障点之一。

我在我的博客文章Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding上展示了所有这些内容

关于c# - 未在MVVM中填充组合框列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46974780/

相关文章:

c# - 将 C# 7 代码部署到 VSTS

wpf - 重用 Viewbox 资源

android - 使用 MVVM 模型在 Xamarin Android 中弹出 View

c# - 如何将多行文本框作为一行保存到文本文件中?

c# 重写 RichTextBox 粘贴函数 - Win Form App

c# - 数据流管道中的全局每 block 错误处理

wpf - 如何为 WPF 应用程序创建 UI 主题

c# - 使 wpf datagrid 行在元素之间单击鼠标时可选择

android - 使用三元运算符在 Android MVVM 数据绑定(bind)中实现可见性

wpf - 在 View 的代码中将 WPF 事件绑定(bind)到 MVVM ViewModel 命令