【发布时间】:2011-05-20 04:27:36
【问题描述】:
我有来自网络服务以ObservableCollection<string> 形式返回的数据我想将集合绑定到只读TextBox,以便用户可以选择数据并将其复制到剪贴板。
为了将集合绑定到 TextBox 的 Text 属性,我创建了 IValueConverter,它将集合转换为文本字符串。这似乎有效,只是它只有效一次,就好像绑定无法识别对 Observable 集合的后续更改。这是一个重现问题的简单应用程序,只是为了确认绑定工作正常,我还绑定到一个“ListBox”
这是不是因为 Text binding simple 不处理集合的 change 事件?
我当然可以选择一个选项来处理集合更改并将这些更改传播到 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();
}
}
}
【问题讨论】:
-
您可能需要引发属性更改事件以更新文本框。
-
@ChrisF,谢谢。我希望更改通知将通过绑定传播到 TextBox。
标签: wpf silverlight data-binding ivalueconverter