0

我正在尝试将文本文件(以及这些文件的名称)中的数据绑定到 C# Metro 风格应用程序中的 ListBox。

我已经检查了 Metro Samples - 但是我无法从它们中获得太多意义。一开始我对 XAML 比较陌生,把它放在 Metro 风格的应用程序之上只会增加混乱。

对于 WinForms 中如此微不足道的任务,感觉就像我正在尝试编写自己的操作系统!

有人可以帮帮我吗?我搜索了又搜索,但最终还是找到了相同的旧教程/文档;也许只有我一个人,但我觉得这方面的文档缺乏。也许它还没有完成?

任何帮助都将不胜感激:)

4

1 回答 1

1

V 声明一个字典并循环遍历所有文件,将名称作为键,将文件的内容作为值。

然后在 XAML 中将列表框绑定到字典中的项目,并将 displaymemberpath 设置为 KeyValuePair 的键。

选择更新将显示您的内容的其他控件时。我会看看我是否可以用代码为你做一个例子。

这里的示例请不要看样式:) 为这个 My ViewModel 使用了 MVVM

namespace WPFTest.ViewModels
{
using System.IO;
using System.Windows.Input;

using Microsoft.Practices.Prism.Commands;

public class MainViewModel : NotificationObject
{
    public MainViewModel()
    {
        FileList = new Dictionary<string, string>();
        FillFileListCommand = new DelegateCommand(FillFileListExecuted);
    }

    private Dictionary<string, string> fileList;

    public Dictionary<string,string> FileList
    {
        get
        {
            return fileList;
        }
        set
        {
            fileList = value;
            RaisePropertyChanged(()=>FileList);
        }
    }

    public ICommand FillFileListCommand { get; set; }
    private void FillFileListExecuted()
    {
        var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var files = Directory.GetFiles(path, "*.txt");
        var dict = new Dictionary<string, string>();
        foreach (var file in files)
        {
            using (var reader = new StreamReader(file))
            {
                var text = reader.ReadToEnd();
                dict.Add(file, text);
            }
        }
        FileList = dict;
    }
}

}

xml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="347*" />
        <RowDefinition Height="414*" />
    </Grid.RowDefinitions>
    <ListBox Height="701" Name="listBox1" Width="302" Margin="12,48,664,0" VerticalAlignment="Top" ItemsSource="{Binding FileList}" DisplayMemberPath="Key" Grid.RowSpan="2" />
    <TextBlock Height="737" HorizontalAlignment="Left" Margin="320,12,0,0" Name="textBlock1" Text="{Binding ElementName=listBox1, Path=SelectedItem.Value}" VerticalAlignment="Top" Width="646" TextWrapping="Wrap" Grid.RowSpan="2" />
    <Button Content="Fill" Height="30" HorizontalAlignment="Left" Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" Width="302" Command="{Binding FillFileListCommand}" />
</Grid>

在 xaml 的代码隐藏中说

DataContext = new MainViewModel();
于 2012-09-14T06:41:30.400 回答