How to display JSON in WPF TreeView

我的未来我决定 提交于 2019-12-04 20:01:14

The problem is that your XAML can only show a collections in dictionary's value and if there is a string, then it will be considered as collection of characters. One of the quick sollutions is to create a converter, which will transform your strings into string collections.

For this you need a value converter(sorry I do code in c#)

public class ValConv : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string str)
        {
            return new List<string> { str };
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}


Instantiate this converter in resources:

<Window.Resources>
<local:ValConv x:key="valKonv"/>
</Window.Resources>


and use it:

<HierarchicalDataTemplate ItemsSource="{Binding Value, Converter={StaticResource valConv}}" >

Here is the code Rekshino submitted, in Vb.

Imports System.Globalization
Public Class ValConv
Implements IValueConverter
Private Function IValueConverter_Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
    If (TypeOf value Is String) Then
        Dim newStr As New List(Of String)
        newStr.Add(value)
        Return newStr
    Else
        Return value
    End If
End Function

Private Function IValueConverter_ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
    Return value
End Function

End Class

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp2"
    Title="Window1" Height="300" Width="300">

<Window.Resources>
    <local:ValConv x:Key="valConv"/>
</Window.Resources>
<Grid>
    <TreeView x:Name="tView">

    <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Value, Converter={StaticResource valConv}}" >
                <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" Foreground="Red"/>
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
            <TextBlock Text="{Binding Key}"/>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>

</TreeView>
</Grid>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!