【发布时间】:2017-02-25 17:12:36
【问题描述】:
我想通过将strings 中的ObservableCollection 绑定到ListBox 的ItemsSource 属性并将项目模板设置为TextBox 来操作它。
我的问题是,当我在 ListBox 包含的 TextBox 项目中编辑 ObservableCollection 中的项目时,它们没有得到更新。我做错了什么?
最小工作示例的 XAML 是
<Window x:Class="ListBoxUpdate.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ListBoxUpdate" Height="300" Width="300"
>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Show items" Click="HandleButtonClick"/>
<TextBlock Grid.Row="1" x:Name="textBlock" />
</Grid>
<ListBox
Grid.Column="1"
ItemsSource="{Binding Strings, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding ., Mode=TwoWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
而相应的代码隐藏是
using System;
using System.Collections.ObjectModel;
using System.Windows;
namespace ListBoxUpdate
{
public partial class Window1 : Window
{
public ObservableCollection<string> Strings { get; set; }
public Window1()
{
InitializeComponent();
Strings = new ObservableCollection<string>(new string[] { "one", "two", "three" });
this.DataContext = this;
}
void HandleButtonClick(object sender, RoutedEventArgs e)
{
string text = "";
for (int i = 0; i < Strings.Count; i++) {
text += Strings[i] + Environment.NewLine;
}
textBlock.Text = text;
}
}
}
非常感谢您的建议。
【问题讨论】:
-
字符串是不可变的,不能更改。如果您希望能够更改文本,您将需要一个带有字符串属性的包装类。然后你可以改变类的属性。
-
@BrandonKramer:非常感谢,你是对的。我用 StringWrapper 内部类替换了字符串,然后它就可以工作了。
-
很高兴我能帮上忙。
-
@BrandonKramer:如果您发表评论作为答案,我应该很高兴接受它。我在这样的论坛上比较缺乏经验,但我认为根据别人的评论回答我自己的问题是不礼貌的。
-
@tethered:实际上,这与
string类型是不可变的没有任何关系。只是因为 WPF 绑定不能改变被绑定的源对象;它只能更改该对象的属性。但是是的,答案仍然是一样的:将要更改的值放在源对象的属性中,而不是使其成为源对象。您应该随时自行回答...布兰登可能不想花时间写一个完整的答案,但您可以轻松发布您必须编写的代码来解决问题,因为您已经拥有它。
标签: c# wpf string data-binding listbox