ObservableCollection <string>绑定文本框(可滚动)wpf c#</string>

时间:2015-01-21 15:41:56

标签: c# wpf textbox observablecollection ivalueconverter

SSH客户端的输出被添加到Results ObservableCollection 我得到了listview中显示的信息。

如何绑定可滚动的只读文本框以列出集合中的所有内容?

<!--<ListView ItemsSource="{Binding Results}" Grid.Row="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="15">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Result" DisplayMemberBinding="{Binding}"/>
                </GridView>
            </ListView.View>
        </ListView>-->

如果有任何帮助,我已经有了转换

public class JoinStringsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var strings = value as IEnumerable<string>;
        return string.Join(Environment.NewLine, strings);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

1 个答案:

答案 0 :(得分:1)

转换器

public class ObservableStringCollectionToMultiLineStringConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        ObservableCollection<string> logEntries = values[0] as ObservableCollection<string>;
        StringBuilder sb = new StringBuilder();
        if (logEntries != null && logEntries.Count > 0)
        {

            foreach (string msg in logEntries)
            {
                sb.AppendLine(msg);
            }

            return sb.ToString();
        }
        else
            return String.Empty;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

文本框元素

<GroupBox Header="Log" Grid.Row="4" Margin="0,10,0,0">
        <TextBox Style="{StaticResource SelectableTextBlockLikeStyle}" VerticalScrollBarVisibility="Auto" ap:TextBoxUtilities.AlwaysScrollToEnd="True" AcceptsReturn="True">
            <TextBox.Text>
                <MultiBinding Converter="{StaticResource ObservableStringCollectionToMultiLineStringConverter}">
                    <Binding Path="IncomingMessages" Mode="OneWay"/>
                    <Binding Path="IncomingMessages.Count" Mode="OneWay" />
                </MultiBinding>
            </TextBox.Text>
        </TextBox>
    </GroupBox>