Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用mvvm填充Listview_C#_Wpf_Listview_Mvvm_Mvvm Light - Fatal编程技术网

C# 使用mvvm填充Listview

C# 使用mvvm填充Listview,c#,wpf,listview,mvvm,mvvm-light,C#,Wpf,Listview,Mvvm,Mvvm Light,我想问一下如何使用MVVM模式填充listview我是MVVM模式的初学者,我从做事情中学到的比阅读更多。我在使用wpf之前就做过,但我使用了代码隐藏 我使用Mvvm灯。我想要的是浏览文件夹的位置,然后用其中的文件填充listview 到目前为止,我已经有一个浏览文件夹 我有这个密码 public class OpenFileDialogVM : ViewModelBase { public static RelayCommand OpenCommand { get; s

我想问一下如何使用MVVM模式填充listview我是MVVM模式的初学者,我从做事情中学到的比阅读更多。我在使用wpf之前就做过,但我使用了代码隐藏

我使用Mvvm灯。我想要的是浏览文件夹的位置,然后用其中的文件填充listview

到目前为止,我已经有一个浏览文件夹

我有这个密码

public class OpenFileDialogVM : ViewModelBase
    {
        public static RelayCommand OpenCommand { get; set; }
        private string _selectedPath;
        public string SelectedPath
        {
            get { return _selectedPath; }
            set
            {
                _selectedPath = value;
                RaisePropertyChanged("SelectedPath");
            }
        }

        private string _defaultPath;

        public OpenFileDialogVM()
        {
            RegisterCommands();
        }

        public OpenFileDialogVM(string defaultPath)
        {
            _defaultPath = defaultPath;
            RegisterCommands();
        }

        private void RegisterCommands()
        {
            OpenCommand = new RelayCommand(ExecuteOpenFileDialog);
        }

        private void ExecuteOpenFileDialog()
        {
            var dialog = new FolderBrowserDialog();
            dialog.ShowDialog();

            SelectedPath = dialog.SelectedPath;
        }
    }
我有这个用户控制代码

<UserControl x:Class="MvvmLight1.FolderDialog"
             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:vm="clr-namespace:MvvmLight1"
             xmlns:local="clr-namespace:MvvmLight1"
             mc:Ignorable="d" d:DesignWidth="300" Height="186.916" >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="90*"/>
            <RowDefinition Height="97*"/>
        </Grid.RowDefinitions>
        <Grid>
            <TextBox Text="{Binding SelectedPath}" />
        </Grid>
        <Grid Grid.Row="1" >
            <Button Command="vm:OpenFileDialogVM.OpenCommand" >Browse</Button>
        </Grid>

    </Grid>
</UserControl>

谢谢您的时间。

您的视图模型应该有一个文件名的
可观察集合

public ObservableCollection<string> FileNames { get; }
    = new ObservableCollection<string>();
然后将列表框的
ItemsSource
属性绑定到该集合:

<ListBox ItemsSource="{Binding FileNames}"/>

  • 使文件成为公共可观察的集合
  • 引发PropertyChanged事件
  • 将窗口的datacontext设置为viewmodel
  • 绑定到xaml中viewmodel的属性
反恐精英
使用系统;
使用系统组件模型;
使用System.IO;
使用System.Windows;
使用System.Windows.Input;
使用System.Collections.ObjectModel;
命名空间StackOverflow_PopulateListView
{
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
DataContext=新的OpenFileDialogVM();
}
}
公共类OpenFileDialogVM:ViewModelBase
{
公共静态RelayCommand OpenCommand{get;set;}
私有字符串_selectedPath=“输入路径”;
公共字符串选择路径
{
获取{return\u selectedPath;}
设置
{
_selectedPath=值;
OnPropertyChanged(“SelectedPath”);
}
}
私有ObservableCollection_files=新的ObservableCollection(){“山雀”、“球”、“屁股”、“山雀”};
公共可观测收集文件
{
获取{return\u files;}
设置
{
_文件=值;
OnPropertyChanged(“文件”);
}
}
专用ICommand _selectFileCommand;
公共ICommand和SelectFileCommand
{
收到
{
返回_selectFileCommand??(_selectFileCommand=newrelaycommand(()=>Call(SelectedPath));
}
保护集
{
_选择FileCommand=value;
}
}
公共作废调用(字符串选择路径)
{
尝试
{
Files=newobserveCollection(Directory.GetFiles(selectedpath,“*”,SearchOption.AllDirectories));
}
捕获(例外情况除外)
{
控制台写入线(例如StackTrace);
掷骰子;
}
}
}
公共类中继命令:ICommand
{
公共行动法案{get;set;}
///当命令的目标应重新评估是否可以执行该命令时发生。
公共事件处理程序CanExecuteChanged;
公共关系委员会(行动法)
{
Act=Act;
}
///返回一个bool,指示是否可以使用给定参数执行命令
公共布尔CanExecute(对象对象对象)
{
返回true;
}
///发送ICommand.CanExecuteChanged
public void ChangeCanExecute()
{
对象发送方=此;
EventArgs EventArgs=null;
CanExecuteChanged(发送方、事件参数);
}
///调用执行操作
公共无效执行(对象obj)
{
Act();
}
}
/// 
///非常通用的ViewModelBase;用于复制粘贴到几乎任何MVVM项目中
/// 
公共类ViewModelBase:INotifyPropertyChanged
{
公共事件属性更改事件处理程序属性更改;
/// 
///激发属性ChangedEventHandler,用于绑定
/// 
受保护的虚拟void OnPropertyChanged(字符串名称)
{
PropertyChanged?.Invoke(这是新的PropertyChangedEventArgs(名称));
}
}
}
XAML


注意:添加System.Windows.FormsYes的参考。你能帮助我或给我一些代码片段如何使用MVVM调用代码吗?在我选择了一个文件夹后,感谢您现在在我的IDE中制作。作为将来的参考,请看如何写一个问题(虽然这是一个相当好的工作)。我很抱歉,英语对我来说是一门外语。下次我会试着把问题问清楚。谢谢你的代码。什么时候以及如何使用mvvm模式调用该代码?非常感谢“选择目录时”,即SelectedPath属性更改时。我刚刚将问题归结为“将xaml listview数据绑定到viewmodel中的文件属性”。这包括独立编译所需的一切。祝你好运谢谢你的工作。现在我只需要搜索那些代码是什么以及我什么时候使用它们。非常感谢你
var files = Directory.EnumerateFiles(selectedpath, "*", SearchOption.AllDirectories);

FileNames.Clear();

foreach (var file in files)
{
    FileNames.Add(file);
}
<ListBox ItemsSource="{Binding FileNames}"/>
    using System;
    using System.ComponentModel;
    using System.IO;
    using System.Windows;
    using System.Windows.Input;
    using System.Collections.ObjectModel;

    namespace StackOverflow_PopulateListView
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                DataContext = new OpenFileDialogVM();
            }
        }

        public class OpenFileDialogVM : ViewModelBase
        {
            public static RelayCommand OpenCommand { get; set; }
            private string _selectedPath = "Enter a Path";
            public string SelectedPath
            {
                get { return _selectedPath; }
                set
                {
                    _selectedPath = value;
                    OnPropertyChanged("SelectedPath");
                }
            }

            private ObservableCollection<string> _files = new ObservableCollection<string>() { "Tits", "balls", "ass", "tits" };
            public ObservableCollection<string> Files
            {
                get { return _files; }
                set
                {
                    _files = value;
                    OnPropertyChanged("Files");
                }
            }

            private ICommand _selectFileCommand;
            public ICommand SelectFileCommand
            {
                get
                {
                    return _selectFileCommand ?? (_selectFileCommand = new RelayCommand(() => Call(SelectedPath)));
                }
                protected set
                {
                    _selectFileCommand = value;
                }
            }

            public void Call(string selectedpath)
            {
                try
                {
                    Files = new ObservableCollection<string>(Directory.GetFiles(selectedpath, "*", SearchOption.AllDirectories));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    throw ex;
                }
            }
        }

        public class RelayCommand : ICommand
        {
            public Action Act { get; set; }

            /// <summary> Occurs when the target of the Command should reevaluate whether or not the Command can be executed. </summary>
            public event EventHandler CanExecuteChanged;

            public RelayCommand(Action act)
            {
                Act = act;
            }

            /// <summary> Returns a bool indicating if the Command can be exectued with the given parameter </summary>
            public bool CanExecute(object obj)
            {
                return true;
            }

            /// <summary> Send a ICommand.CanExecuteChanged </summary>
            public void ChangeCanExecute()
            {
                object sender = this;
                EventArgs eventArgs = null;
                CanExecuteChanged(sender, eventArgs);
            }

            /// <summary> Invokes the execute Action </summary>
            public void Execute(object obj)
            {
                Act();
            }
        }

        /// <summary>
        /// Extremely generic ViewModelBase; for copy-pasting into almost any MVVM project
        /// </summary>
        public class ViewModelBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;

            /// <summary>
            /// Fires PropertyChangedEventHandler, for bindables
            /// </summary>
            protected virtual void OnPropertyChanged(string name)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            }

        }
    }
<Window x:Class="StackOverflow_PopulateListView.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:StackOverflow_PopulateListView"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525"
    >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="8*"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>

        <ListView ItemsSource="{Binding Files}" Grid.Row="0">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <TextBox Grid.Row="1"
                    Text="{Binding SelectedPath}"
                />

        <Button Grid.Row="2"
                    Content="Call"
                    Command="{Binding SelectFileCommand}"
                />

    </Grid>
</Window>