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();