none
How to add Treeview Item in Treeview RRS feed

  • Question

  • Hi All,

    I have a treeview which i fill from DB. I fill each item by clearing it's childitems because they will be doubled , how  can i check while adding whether this element is present in childitems of this item or not.


    Thanks & Regards dhampall

    Tuesday, August 28, 2012 2:07 PM

Answers

  • Hi again

     

    TBH if it were me, I'd have converted the db data into a collection of object, either manually or with Entity Framework. Then I'd bind the TreeView ItemsSource to that. Then changes are checked against my nice local databound collection. Changes are made to the collection and reflected in the TreeView.

    Here is an example. Albeit a Silverlight example, but still the same principle.

    So the proper answer is, place the data in the code, where you can check it and change it, then bind the TreeView to this source data. Even if this just means exposing the DataTable as a whole in code and binding to DataTable.DefaultView. Then you have the DataTable in code to interrogate and manipulate.

    Example using DataGrid, but same ItemsSource principle.

     

    Lecture aside, if you really want to navigate the TreeView items, the problem is of course that they don't exist in the VisualTree until you expand them, so you have to use the ItemContainerGenerator, as described below:

    http://social.msdn.microsoft.com/Forums/en/wpf/thread/0fbd6942-6c3f-4bb5-bc72-f9bc4ed5d808

     

    Regards,
    Pete


    #PEJL

    Tuesday, August 28, 2012 3:46 PM
    Moderator
  • Hi dhampall_79,

    If you want to check if the item is existed in your treeview, you could refer to this document:

    http://msdn.microsoft.com/en-us/library/ff407130.aspx

    If return item is null, you could add it into your TreeView,

    Best regards,


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, August 29, 2012 7:58 AM
    Moderator

All replies

  • Hi again

     

    TBH if it were me, I'd have converted the db data into a collection of object, either manually or with Entity Framework. Then I'd bind the TreeView ItemsSource to that. Then changes are checked against my nice local databound collection. Changes are made to the collection and reflected in the TreeView.

    Here is an example. Albeit a Silverlight example, but still the same principle.

    So the proper answer is, place the data in the code, where you can check it and change it, then bind the TreeView to this source data. Even if this just means exposing the DataTable as a whole in code and binding to DataTable.DefaultView. Then you have the DataTable in code to interrogate and manipulate.

    Example using DataGrid, but same ItemsSource principle.

     

    Lecture aside, if you really want to navigate the TreeView items, the problem is of course that they don't exist in the VisualTree until you expand them, so you have to use the ItemContainerGenerator, as described below:

    http://social.msdn.microsoft.com/Forums/en/wpf/thread/0fbd6942-6c3f-4bb5-bc72-f9bc4ed5d808

     

    Regards,
    Pete


    #PEJL

    Tuesday, August 28, 2012 3:46 PM
    Moderator
  • Hi dhampall_79,

    If you want to check if the item is existed in your treeview, you could refer to this document:

    http://msdn.microsoft.com/en-us/library/ff407130.aspx

    If return item is null, you could add it into your TreeView,

    Best regards,


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, August 29, 2012 7:58 AM
    Moderator
  • Hi dhampall_79

    Try this sample(Create Project named Helper and copy-paste the rest)

    xaml:

            

    <Window x:Class="Helper.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <Window.Resources>
            <HierarchicalDataTemplate x:Key="TodoTemplate" ItemsSource="{Binding Children}" >
                <WrapPanel>
                    <CheckBox IsChecked="{Binding IsChecked}"  />
                    <TextBlock Text="{Binding TodoHeader}" FontWeight="{Binding FontWeight}" Margin="10, 0, 0, 0" />
                </WrapPanel>
            </HierarchicalDataTemplate>
        </Window.Resources>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="20" />
            </Grid.RowDefinitions>
            <TreeView x:Name="TreeTodo" Background="PaleGreen" AllowDrop="True"
                      ItemsSource="{Binding Projects}"
                      ItemTemplate="{StaticResource TodoTemplate}">
                <TreeView.ItemContainerStyle>
                    <Style TargetType="{x:Type TreeViewItem}">
                        <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                    </Style>
                </TreeView.ItemContainerStyle>
            </TreeView>

            <StackPanel Orientation="Horizontal" Grid.Row="1">
                <TextBox x:Name="TextNew" Background="Aqua" Width="200" />
                <Button Content="Add" Click="Button_Click" />
            </StackPanel>

        </Grid>
    </Window>

    cs:

               

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.ComponentModel;
    using System.Collections.ObjectModel;

    namespace Helper
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            private ObservableCollection<Todo> mProjects;

            private ObservableCollection<Todo> temp;
            Todo mTodo;

            public Window1()
            {
                InitializeComponent();
                DataContext = this;

                if (mProjects == null)
                {
                    mProjects = new ObservableCollection<Todo>();
                }
                mTodo = new Todo() { TodoHeader = "A" };
                mTodo.Children.Add(new Todo() { TodoHeader = "A.a" });
                mProjects.Add(mTodo);

                mProjects.Add(new Todo() { TodoHeader = "B" });
                mProjects.Add(new Todo() { TodoHeader = "C" });
                mProjects.Add(new Todo() { TodoHeader = "D" });
                temp = mProjects;
            }

            public ObservableCollection<Todo> Projects
            {
                get
                {
                    return mProjects;
                }

            }

            private void Button_Click(object sender, RoutedEventArgs e)
            {
                string newString = TextNew.Text;
                if (!String.IsNullOrEmpty(newString))
                {
                    if (!IsSuchItemExist(newString))
                    {
                        mTodo.Children.Add(new Todo() { TodoHeader = newString });
                    }
                    else
                    {
                        MessageBox.Show("Already exist");
                    }

                }
            }

            private bool IsSuchItemExist(string newString)
            {
                foreach (Todo todo in mTodo.Children)
                { 
                    if (todo.TodoHeader.Equals(newString))
                    {
                        return true;
                    }
                }
                return false;
            }
        }
    }

    Todo:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
    using System.Windows;
    using System.ComponentModel;

    namespace Helper
    {
        public class Todo : INotifyPropertyChanged
        {
            private bool mIsChecked;
            public bool IsChecked
            {
                get
                {
                    return mIsChecked;
                }
                set
                {
                    mIsChecked = value;
                }
            }


            private bool mIsExpanded;
            public bool IsExpanded
            {
                get
                {
                    return mIsExpanded;
                }
                set
                {
                    mIsExpanded = value;
                    if (value)
                    {
                        this.FontWeight = FontWeights.Bold;
                    }
                    else
                    {
                        this.FontWeight = FontWeights.Normal;
                    }
                }
            }
            private string mTodoHeader;
            public string TodoHeader
            {
                get
                {
                    return mTodoHeader;
                }
                set
                {
                    mTodoHeader = value;
                }
            }

            FontWeight mFontWeight = FontWeights.Normal;
            public FontWeight FontWeight
            {
                get
                {
                    return mFontWeight;
                }
                set
                {
                    mFontWeight = value;
                    OnPropertyChanged("FontWeight");
                    
                }
            }

            #region INotifyPropertyChanged Members

            public event PropertyChangedEventHandler PropertyChanged;

            void OnPropertyChanged(string property)
            {
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs(property));
                }
            }

            #endregion
            

            private ObservableCollection<Todo> mChildren;
            public ObservableCollection<Todo> Children
            {
                get
                {
                    if (mChildren == null)
                    {
                        mChildren = new ObservableCollection<Todo>();
                    }
                    return mChildren;
                }
            }
        }
    }

    Please let me know if you have any query.

    Regards

    Ashish

    -------------------------------------------------------------------------

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".



    Wednesday, August 29, 2012 9:45 AM
  • Hi dhampall_79,
     
    I am marking your issue as "Answered", if you have new findings about your issue, please let me know.

     

    Best regards,


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, September 6, 2012 9:22 AM
    Moderator