【问题标题】:Binding properties of selected object in combobox to TextBox in WPF将组合框中选定对象的属性绑定到 WPF 中的 TextBox
【发布时间】:2012-09-09 05:31:40
【问题描述】:

我正在使用 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?

【问题讨论】:

    标签: wpf mvvm binding combobox textbox


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,没想到会这么简单:)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      相关资源
      最近更新 更多