c# - 如何将字符串属性绑定(bind)到 ListBox 中的 TextBox

标签 c# wpf mvvm listbox

我正在绑定(bind) List<string>到我的ListBox在 WPF 中使用 MVVM

目前我有

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

我的 ViewModel 中的文件内容很简单

public List<string> FileContents {get;set;}

并且 FileContents 值在 ViewModel 的构造函数中设置,因此无需担心 INotifyProperty

目前一切正常。我可以在我的 ListBox 中看到列表随心所欲。

现在我需要提供一个模板!这是错误的地方

<ListBox ItemsSource="{Binding FileContents}">
     <ListBox.ItemTemplate>
          <DataTemplate>
              <TextBox Text="{Binding}" />
           </DataTemplate>
     </ListBox.ItemTemplate>
 </ListBox>

这就是问题所在!我的理解是我只需要做 <TextBox Text = "{Binding}"因为 ListBox 已经绑定(bind)到 List<string>属性(称为 FileContents)

但是,当我运行上面的 Visual Studio 时

The application is in break mode

如果我将代码更新为

<TextBox Text = "Some String Value"

然后它工作正常

我不明白我做错了什么。

最佳答案

设置ModeBindingOneWay :

<TextBox Text="{Binding Path=., Mode=OneWay}" />

Text 的默认绑定(bind)模式TextBox 的属性是TwoWay但是当你绑定(bind)到 string 时这将不起作用在List<string> .

关于c# - 如何将字符串属性绑定(bind)到 ListBox 中的 TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48283255/

相关文章:

c# - 如何在 Word 共享加载项中挂接按键事件?

wpf - 在 WPF TreeView 中递归绑定(bind)

android - Observe Kotlin 中的返回值

c# - 在另一个 IList 数据模型中存储 Array 或 IList

java - Web 服务 setter 不工作

c# - 非泛型类中的泛型方法

C# 网站 - 分析代码和查询

c# - 使用 XAML/WPF 的路径/矢量的(自动)动画

wpf - 如何自动缩放一组控件的字体大小?

c# - 为什么这个 ListView 不会随着绑定(bind)属性的变化而改变?