Raphael Teyssandier
Raphael Teyssandier

Reputation: 1777

TreeView ItemsSource MVVM Binding

i have a TreeView with default treeviewitem, and another with dynaic value. But instead of having name of the TreeViewItem, i have that: https://gyazo.com/00563993faf7f5d59bb8ab6870fd428d

The entire line is : "MyWindowsMediaPlayer.Model.PlaylistDB"

XAML:

<TreeView Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="135">
            <TreeViewItem Header="Bibliotheque" IsExpanded="True">
                <TreeViewItem Header="Mes Musiques" IsSelected="True"></TreeViewItem>
                <TreeViewItem Header="Mes Videos"></TreeViewItem>
                <TreeViewItem Header="Mes Images"></TreeViewItem>
            </TreeViewItem>
            <TreeViewItem Header="Lecteur"></TreeViewItem>
            <TreeViewItem Header="Playlist" ItemsSource="{Binding ItemSourceTree}">
            </TreeViewItem>
        </TreeView>

CS:

private ObservableCollection<PlaylistDB> _itemSourceTree;
public ObservableCollection<PlaylistDB> ItemSourceTree
        {
            get { return this._itemSourceTree; }
            set
            {
                this._itemSourceTree = value;
                this.OnPropertyChanged("ItemSourceTree");
            }
        }

And at the Initialization:

this.ItemSourceTree.Add(new PlaylistDB() { NamePlaylist = "I'm a test" });
this.ItemSourceTree.Add(new PlaylistDB() { NamePlaylist = "I'm a test 2 " });

Upvotes: 0

Views: 2344

Answers (2)

user1672994
user1672994

Reputation: 10849

You have to define the DataTemplate under TreeView resources to define the template how UI should render TreeViewItem's bind ViewModel.

 <DataTemplate DataType="{x:Type local:PlaylistDB}">
          <StackPanel Orientation="Horizontal">
             <TextBlock Text="{Binding NamePlaylist }" />
          </StackPanel>
 </DataTemplate>

Upvotes: 1

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

Your Tree View don´t know how to display the PlaylistDB object.

Override the ToString() Methode of your PlaylistDB like this:

public override string ToString()
{
  return "NameOfElement";
}

Also you could edit your TreeView Resource like described here: http://www.wpf-tutorial.com/treeview-control/treeview-data-binding-multiple-templates/

Upvotes: 1

Related Questions