Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9274105
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T16:16:35+00:00 2026-06-18T16:16:35+00:00

I’m trying to write a mutli select treeview behavior, however while doing so I’m

  • 0

I’m trying to write a mutli select treeview behavior, however while doing so I’m getting this cryptic error “Items collection must be empty before using ItemsSource.”

The following is my xaml code:

<Window x:Class="TreeView.Spike.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Spike="clr-namespace:TreeView.Spike" 
         Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width=".5*"/>
            <ColumnDefinition Width=".5*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="40"></RowDefinition>
        </Grid.RowDefinitions>

        <TreeView ItemsSource="{Binding Nodes}" Grid.Row="0" x:Name="treeView" Grid.Column="0">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}">                  
                    </TextBlock>
                    </StackPanel>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
            <TreeView.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Add"></MenuItem>
                    <MenuItem Header="Delete"></MenuItem>
                </ContextMenu>
            </TreeView.ContextMenu>
            <Spike:MultipleItemSelectionAttachedBehavior AllSelectedItems="{Binding Path=AllSelectedNodes}"/>
        </TreeView>

    </Grid>
</Window>

My attached behavior:

 public class MultipleItemSelectionAttachedBehavior:Behavior<System.Windows.Controls.TreeView>
    {
        public static DependencyProperty AllSelectedItemsProperty =
        DependencyProperty.RegisterAttached("AllSelectedItems", typeof(object), typeof(MultipleItemSelectionAttachedBehavior),
    new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Inherits));

        private static readonly PropertyInfo IsSelectionChangeActiveProperty = typeof(System.Windows.Controls.TreeView).GetProperty("IsSelectionChangeActive",
          BindingFlags.NonPublic | BindingFlags.Instance);

        public object AllSelectedItems
        {
            get
            {
                return (object)GetValue(AllSelectedItemsProperty);
            }
            set
            {
                SetValue(AllSelectedItemsProperty, value);
            }
        }

        public static bool GetAllSelectedItems(DependencyObject obj)
        {
            return (bool)obj.GetValue(AllSelectedItemsProperty);
        }

        public static void SetAllSelectedItems(DependencyObject obj, bool value)
        {
            obj.SetValue(AllSelectedItemsProperty, value);
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.SelectedItemChanged += AssociatedObject_SelectedItemChanged;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.SelectedItemChanged -= AssociatedObject_SelectedItemChanged;
        }

        void AssociatedObject_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (IsSelectionChangeActiveProperty == null) return;

            var selectedItems = new List<Node>();

            var treeViewItem = AssociatedObject.SelectedItem as Node;
            if (treeViewItem == null) return;

            // allow multiple selection
            // when control key is pressed
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                var isSelectionChangeActive = IsSelectionChangeActiveProperty.GetValue(AssociatedObject, null);

                IsSelectionChangeActiveProperty.SetValue(AssociatedObject, true, null);
                selectedItems.ForEach(item => item.IsSelected = true);

                IsSelectionChangeActiveProperty.SetValue(AssociatedObject, isSelectionChangeActive, null);
            }
            else
            {
                // deselect all selected items except the current one
                selectedItems.ForEach(item => item.IsSelected = (item == treeViewItem));
                selectedItems.Clear();
            }

            if (!selectedItems.Contains(treeViewItem))
            {
                selectedItems.Add(treeViewItem);
            }
            else
            {
                // deselect if already selected
                treeViewItem.IsSelected = false;
                selectedItems.Remove(treeViewItem);
            }

            AllSelectedItems = selectedItems;
        }
    }

..and my ViewModel

public class ViewModel :NotificationObject
    {
        public ViewModel()
        {
            AllSelectedNodes = new ObservableCollection<Node>();
        }
 private ObservableCollection<Node> _allSelectedNodes;
        public ObservableCollection<Node> AllSelectedNodes
        {
            get { return _allSelectedNodes; }
            set
            {
                _allSelectedNodes = value;
                RaisePropertyChanged(() => AllSelectedNodes);   
            }
        }
}

My Model:

public class Node:NotificationObject
    {

        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged(() => Name);   
            }
        }




        private bool _isExpanded = true;
        public bool IsExpanded
        {
            get { return _isExpanded; }
            set
            {
                _isExpanded = value;
                RaisePropertyChanged(() => IsExpanded); 
            }
        }

        private bool _isSelected;

        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                _isSelected = value;
                RaisePropertyChanged(() => IsSelected);

            }
        }

        private ObservableCollection<Node> _nodes;
        public ObservableCollection<Node> Nodes
        {
            get { return _nodes; }
            set
            {
                _nodes = value;
                RaisePropertyChanged(() => Nodes);  
            }
        }

        public static IList<Node> Create()
        {
            return new List<Node>()
                       {
                           new Node()
                               {
                                   Name = "Activity",
                                   Nodes = new ObservableCollection<Node>()
                                               {
                                                   new Node() {Name = "Company",Nodes = new ObservableCollection<Node>(){  new Node() {Name = "Company1",Existing = false}}},
                                                     new Node() {Name = "Strategy",Nodes = new ObservableCollection<Node>(){  new Node() {Name = "Strategy1"}}},
                                                        new Node() {Name = "Vehicle",Nodes = new ObservableCollection<Node>(){  new Node() {Name = "Vehicle1",Existing = false}}}
                                               }
                               }
                       };
        }
    }

..and my initialization clode:

   public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var viewModel = new ViewModel();
            this.DataContext = viewModel;
            viewModel.Nodes = new ObservableCollection<Node>(Node.Create());

        }
}

I have no clue what is going wrong here, could you please help?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T16:16:37+00:00Added an answer on June 18, 2026 at 4:16 pm

    You’re missing the <i:Interaction.Behaviors> element:

    replace:

    <Spike:MultipleItemSelectionAttachedBehavior AllSelectedItems="{Binding Path=AllSelectedNodes}"/>

    for:

    <i:Interaction.Behaviors>
        <Spike:MultipleItemSelectionAttachedBehavior AllSelectedItems="{Binding Path=AllSelectedNodes}"/>
    </i:Interaction.Behaviors>
    

    The problem is that the default content property for the TreeView is its Items property, therefore putting that XAML element of the behavior inside of the TreeView element without specifying the <i:Interaction.Behaviors> Attached property, is telling WPF that you want your behavior as an Item in the TreeView, therefore when trying to set its ItemsSource property you recieve the error, because there is already an Item inside of it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to select an H1 element which is the second-child in its group
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I am trying to render a haml file in a javascript response like so:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.