列表框未使用绑定填充 [英] Listbox is not Populating using binding
问题描述
我正在尝试使用mvvm模式在c#wpf中转换现有程序.
I am trying to convert my existing program in c# wpf, using mvvm pattern.
第一部分是选择要处理的文件的文件夹"位置并填充列表框
The first part is select the Folder location of the files to be process and populate the listbox
我在这里找到了使用Mvvm Light的示例:具有MVVM模式的WPF OpenFileDialog?
I found an example here using Mvvm Light: WPF OpenFileDialog with the MVVM pattern?
上面链接中的示例是选择一个文件夹.
the example in the link above is selecting a Folder.
这是我项目的结构
this is the structure of my project
这是我的FileListView.xaml的代码
this is the code of my 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
this is my list which reside in ViewModel\OpenFileDialogVM.cs
public System.Collections.ObjectModel.ObservableCollection<string> FileNames { get; }
= new System.Collections.ObjectModel.ObservableCollection<string>();
这是我用于填充列表的代码.但这不起作用
this is my code for populating the list. but it doesn't work
var files = System.IO.Directory.EnumerateFiles(SelectedPath, "*", System.IO.SearchOption.AllDirectories);
FileNames.Clear();
foreach (var file in files)
{
FileNames.Add(file);
Console.WriteLine(file);
}
我上面的代码有什么问题?
What is wrong with my code above?
代码更新:
在我的文件夹结构上,我有ViewModel文件夹,在其中有OpenFileDialogVm.css
On my folder structure I have ViewModel Folder and inside it I have OpenFileDialogVm.css
但是为什么IDE只识别ViewModelLocator.
but why is it that the IDE only recognize the ViewModelLocator.
我什至构建项目.
我什至在FileListView用户控件的CodeBehind中设置了DataContext,但仍然没有填充列表框
I even set the DataContext in the CodeBehind of FileListView user control but still it doesn't populate the listbox
public partial class FilesListView : UserControl
{
public FilesListView()
{
DataContext = new OpenFileDialogVM();
InitializeComponent();
}
}
推荐答案
将其添加到您的UserControl中:
Add it to your UserControl:
<UserControl
.....
xmlns:viemodels="clr-namespace:MvvmLight1.ViewModels"
/>
<UserControl.DataContext>
<viemodels:OpenFileDialogVM/>
</UserControl.DataContext>
....
</UserControl>
这篇关于列表框未使用绑定填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!