Question

I'm using MvvmLight to manipulate a treeview control.The binding is OK,and my Treeview can get data from its ViewModel.However,something weird happened.

In the ViewModel,I have a string type property:

private string foo;
public string Foo
{
    get { return foo; }
    set
    {
        if (foo== value)
            return;
        foo= value;
        RaisePropertyChanged("Foo");
    }
}

In the ViewModel's Constructor,I initialized Foo:

Foo = "Marry has a little lamb";

In the View,I bind Foo to treeview:

<TreeView HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
          ItemsSource="{Binding Foo}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate>
            <TextBlock Text="{Binding}" HorizontalAlignment="Stretch"
                       VerticalAlignment="Stretch" Foreground="BurlyWood"/>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

I expected the treeview to show "Mary has a little lamb".But instead,it shows

M
a
r
r
...

Apparently,it has treated every single letter as an item.I've tried to change Foo's type to ObservableCollection<string>.Though it works,for some reason,I don't want to change Foo's type.What's the cause of this strange behavior,and how to solve it?

Était-ce utile?

La solution

I think it's because you're binding the TreeView to your property that is a String.
The tree expects a collection of some type, and finds a string. It thinks, hey, I know what string is ... it's a collection of chars ... and off he goes chopping marry and her poor lamb.

So, you either have to "box" your strings into a collection, or change your strategy :)

Edit: some more info, in case someone else stumbles upon this:

From MSDN: ItemsControl.ItemsSource Property :

[BindableAttribute(true)]
public IEnumerable ItemsSource { get; set; }

And having some fun with it:

var an_int = 4;
var a_string = "poor poor marry";
int[] an_array = new int[3] {1,2,3};

if (an_int is IEnumerable)
    Console.WriteLine("you shouldn't see this");

if (a_string is IEnumerable)
    Console.WriteLine("you should see this, as IEnumerable char");

if (an_array is IEnumerable)
    Console.WriteLine("you should see this, as IEnumerable int");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top