我从Web服务中得到的数据是一个
为了将集合绑定到TextBox的Text属性上,我创建了一个
这是因为Text绑定不能处理集合的更改事件吗?
当然,一个选项是我处理集合的更改并将其传播到TextBox绑定的Text属性,这很好,但我想知道为什么对我来说似乎显而易见的解决方案没有按预期工作。 XAML
ObservableCollection<string>
,我想将这个集合绑定到只读的TextBox
上,以便用户可以选择并复制数据到剪贴板。为了将集合绑定到TextBox的Text属性上,我创建了一个
IValueConverter
,将集合转换为文本字符串。这似乎有效,但它只能工作一次,就好像绑定不能识别ObservableCollection的后续更改。以下是一个简单的应用程序,重现了这个问题,仅仅为了确认绑定是否正确,我还绑定了`ListBox`。这是因为Text绑定不能处理集合的更改事件吗?
当然,一个选项是我处理集合的更改并将其传播到TextBox绑定的Text属性,这很好,但我想知道为什么对我来说似乎显而易见的解决方案没有按预期工作。 XAML
<Window x:Class="WpfTextBoxBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfTextBoxBinding"
Title="MainWindow" Height="331" Width="402">
<StackPanel>
<StackPanel.Resources>
<local:EnumarableToTextConverter x:Key="EnumarableToTextConverter" />
</StackPanel.Resources>
<TextBox Text="{Binding TextLines, Mode=OneWay, Converter={StaticResource EnumarableToTextConverter}}" Height="100" />
<ListBox ItemsSource="{Binding TextLines}" Height="100" />
<Button Click="Button_Click" Content="Add Line" />
</StackPanel >
</Window>
后台代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Globalization;
namespace WpfTextBoxBinding
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<string> TextLines {get;set;}
public MainWindow()
{
DataContext = this;
TextLines = new ObservableCollection<string>();
// Add some initial data, this shows that the
// TextBox binding works the first time
TextLines.Add("First Line");
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
TextLines.Add("Line :" + TextLines.Count);
}
}
public class EnumarableToTextConverter : IValueConverter
{
public object Convert(
object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value is IEnumerable)
{
StringBuilder sb = new StringBuilder();
foreach (var s in value as IEnumerable)
{
sb.AppendLine(s.ToString());
}
return sb.ToString();
}
return string.Empty;
}
public object ConvertBack(
object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}