2

我正在使用 MVVM 加载文本文件并显示它们的内容。

模型

MyFile.cs有一个NameText// 实现 INotifyPropertyChanged

MyFileRepository.cs// 我加载的文件的集合

视图模型

OpenFileCommand加载文件并将其添加到 _filerepository 对象

FileCollection绑定到视图

看法

Button解雇OpenCommand

ComboBox显示加载文件的名称

TextBox在 combobx 中显示所选文件的内容

<Button Name="OpenFile" Command="{Binding OpenFileCommand}">
<ComboBox  Name="FilesList" ItemsSource="{Binding Path=FileCollection}" DisplayMemberPath="Name" />
<TextBox Name="FileContent" Text="{Binding the Text of selected file in combobx "/>

如何将combobx中选择的MyFile的Text属性绑定到TextBox?

4

2 回答 2

7

最简单的方法是元素绑定:

<TextBox Name="FileContent"
         Text="{Binding SelectedItem.Text,ElementName=FilesList} />

所以这绑定到 FilesList ComboBox 中 SelectedItem 的 Text 属性,它(如果一切都按照我认为的方式连接)是 MyFile 类型。

于 2012-09-17T00:48:03.890 回答
0

如果没有元素绑定,您可以将属性“SelectedItem”(类型:MyFile)添加到您的 VM 并将其绑定到您的组合框的 SelectedItem 属性(mode=twoway)。现在您的 TextBox.Text-Property 应该如下所示:

<TextBox Name="FileContent"
         Text="{Binding SelectedItem.Text} />
于 2012-09-17T08:32:18.710 回答