【问题标题】:Listbox is not Populating using binding列表框未使用绑定填充
【发布时间】:2017-10-08 15:57:30
【问题描述】:

我正在尝试使用 mvvm 模式在 c# wpf 中转换我现有的程序。

第一部分是选择要处理的文件的文件夹位置并填充列表框

我在这里找到了一个使用 Mvvm Light 的示例:WPF OpenFileDialog with the MVVM pattern?

以上链接中的示例是选择文件夹。

这是我项目的结构

这是我的 FileListView.xaml 的代码

<UserControl x:Class="MvvmLight1.Views.FilesListView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MvvmLight1.Views"
             mc:Ignorable="d" 
             d:DesignHeight="300" Width="730.029">

    <Grid>
        <ListBox ItemsSource="{Binding FileNames}" Margin="5,5,5,5"/>

    </Grid>
</UserControl>

这是我在 ViewModel\OpenFileDialogVM.cs 中的列表

public System.Collections.ObjectModel.ObservableCollection<string> FileNames { get; }
    = new System.Collections.ObjectModel.ObservableCollection<string>();

这是我用于填充列表的代码。但它不起作用

var files = System.IO.Directory.EnumerateFiles(SelectedPath, "*", System.IO.SearchOption.AllDirectories);

            FileNames.Clear();

            foreach (var file in files)
            {
                FileNames.Add(file);
                Console.WriteLine(file);
            }

我上面的代码有什么问题?


代码更新:

在我的文件夹结构中,我有 ViewModel 文件夹,里面有 OpenFileDialogVm.css

但为什么 IDE 只识别 ViewModelLocator。

我什至构建项目。

我什至在 FileListView 用户控件的 CodeBehind 中设置了 DataContext,但它仍然没有填充列表框

public partial class FilesListView : UserControl
    {
        public FilesListView()
        {
            DataContext = new OpenFileDialogVM();
            InitializeComponent();

        }
    }

【问题讨论】:

  • 在哪里设置 FilesListView 的 DataContext?
  • 什么不起作用?是否未填充 files 变量或未填充 ListBox?
  • @Rekshino 我没有设置它。我需要在哪里设置它?而且我什至不知道我需要设置它。谢谢
  • @sachin 变量已填充。我使用 for 循环在控制台中写入文件名及其工作
  • 您需要了解 DataContext 在 WPF 中的工作原理。它从根(通常是窗口)流经可视树(这就是为什么您永远不想将 DataContext 绑定到可视树本身{Binding RelativeSource={RelativeSource Self}})。但是如果没有设置,你的绑定将不起作用,因为没有什么可以绑定的。您可以使用像 Snoop 这样的工具在运行时检查 DataContext 和您的绑定。

标签: c# wpf xaml mvvm listbox


【解决方案1】:

将其添加到您的用户控件:

<UserControl
.....
xmlns:viemodels="clr-namespace:MvvmLight1.ViewModels"
/>
    <UserControl.DataContext>
        <viemodels:OpenFileDialogVM/>
    </UserControl.DataContext>
....
</UserControl>

【讨论】:

  • 我试过你的代码,但它不起作用。 IDE 无法识别 viemodels:OpenFileDialogVM。我什至在后面的代码中设置了数据内容。但它仍然没有填充列表框。谢谢
  • 我不确切知道您的 ViewModel 类的名称是什么以及它所在的命名空间。该类必须具有 public 修饰符,并且您的 ViewModel 项目必须在 View 项目中引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多