pfinferno
pfinferno

Reputation: 1945

Get checked items in treeview

I'm using a third party .dll which contains a type of object called Layer. I have a collection of these layers in my viewmodel. In my view, I have a TreeView whose ItemsSource is bound to the collection of layers. I also have a checkbox with each item.

I want to somehow get the all of the checked Layer items.

Normally I would have just make a public boolean property called IsChecked in the object's class, but Layer does not have a property for that.

Here's the xaml:

<TreeView Grid.Row="1" Grid.Column="0">
    <TreeViewItem Header="Shape Files" ItemsSource="{Binding Layers}" >
        <TreeViewItem.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <CheckBox Content="{Binding Name}" />
                </StackPanel>
            </DataTemplate>
        </TreeViewItem.ItemTemplate>
    </TreeViewItem>
</TreeView>

Here's the view model:

public ObservableCollection<Layer> Layers
{
    get { return mapModel.Layers; }
    set { mapModel.Layers = value; OnPropertyChanged("Layers"); }
}

And here's an example of what this looks like:

enter image description here

I know one way would be to have the checked function of the checkboxes bind to a command, with the item itself being sent as a command parameter. Is that really the best way to do this though?

Upvotes: 0

Views: 954

Answers (1)

Alex.Wei
Alex.Wei

Reputation: 1883

Bind another ObservableCollection<Layer> object to TreeView.Tag. Register CheckBox's Checked and Unchecked event. In code behind, the sender's DataContext property should contain a Layer object. Add or remove it from the ObservableCollection<Layer> object that bound to TreeView.Tag depend on which event you are handling. You can access the ObservableCollection<Layer> object from view model any time, you will alway get all the Layer objects that has been selected.

In my opinion, this solution is most effective one, and dosn't voilate any MVVM principle. If you think use a type that was defined in lower layer in view is not acceptable, cast TreeView.Tag to a IList interface could simply avoid that.

Upvotes: 1

Related Questions