Задать вопрос
  • Как реализовать TreeView список с возможностью самостоятельного добавления в него элементов?

    yarosroman
    @yarosroman
    C# the best
    public class TreeNode
        {
            public int ParentId { get; set; }
            public string Name { get; set; }
            public ObservableCollection<TreeNode> Children { get; set; }
        }
    
        public class TreeViewModel
        {
            public ObservableCollection<TreeNode> Nodes { get; set; }
    
            public TreeNode SelectedNode { get; set; }
        }
    
        public partial class MainWindow : Window
        {
            public TreeViewModel model { get; set; }
    
            private int i = 1;
    
            public MainWindow()
            {
                InitializeComponent();
    
                model = new TreeViewModel();
    
                model.Nodes = new ObservableCollection<TreeNode>();
                this.DataContext = model;
    
                model.Nodes.Add(new TreeNode() { Name = "Root", Children = new ObservableCollection<TreeNode>() });
                model.Nodes.FirstOrDefault().Children.Add(new TreeNode() { Name = "Second" });
    
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                if (model.SelectedNode != null)
                {
                    model.SelectedNode.Children.Add(new TreeNode() { Name = "Children "+i.ToString(), Children = new ObservableCollection<TreeNode>() });
                }
                else
                {
                    model.Nodes.Add(new TreeNode() { Name = "Root "+i.ToString(), Children = new ObservableCollection<TreeNode>() });
                }
                i++;
            }
    
            private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
            {
                model.SelectedNode = (TreeNode)e.NewValue;
            }
        }

    <Grid>
            <TreeView HorizontalAlignment="Left" Height="337" Margin="42,34,0,0" VerticalAlignment="Top" Width="303" ItemsSource="{Binding Path=Nodes}">
                <TreeView.ItemTemplate>
    				<HierarchicalDataTemplate ItemsSource="{Binding Children}">
    					<TextBlock Text="{Binding Name}" />
    				</HierarchicalDataTemplate>
    			</TreeView.ItemTemplate>
            </TreeView>
            <Button Content="Button" HorizontalAlignment="Left" Margin="374,34,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
        </Grid>


    1. Использовать для привязываемых коллекций - ObservableCollection - умеет оповещать подписчика об изменении коллекции
    2. WPF не умеет привязывает SelectedItem у TreeView, решения- https://stackoverflow.com/questions/7153813/wpf-mv... , https://tyrrrz.me/blog/wpf-treeview-selecteditem-t...
    Ответ написан
    Комментировать
  • Как можно реализовать привязку данных TreeView к RichTextBox?

    firedragon
    @firedragon
    Не джун-мидл-сеньор, а трус-балбес-бывалый.
    Первые 2 класса хранят данные, загружают из бд, ну тут сами придумаете. См LoadData
    Последний это форма обрабатываются события NodeMouseClick и TextChanged на текст боксах.
    Логика простейшая, но это в общем то пример, в реальности усложните по вкусу.
    using System.Collections.Generic;
    
    namespace TreeViewBinding.Code
    {
        public class TreeSource
        {
            public TreeSource()
            {
                Leaves = new List<TreeLeaf>();
            }
            public List<TreeLeaf> Leaves { get; set; }
    
            /// <summary>
            /// Load data stub. In this example use mock data. In real application load data from database or web service
            /// </summary>
            public void LoadData()
            {
                var first = new TreeLeaf { Description = "First description", Title = "First" };
                var firstSubs = new[]
                {
                    new TreeLeaf(first){Description = "First desc",Title = "First"},
                    new TreeLeaf(first){Description = "Second desc",Title = "Second"},
                    new TreeLeaf(first){Description = "Third desc",Title = "Third"}
                };
                first.Leaves.AddRange(firstSubs);
                var second = new TreeLeaf { Description = "Second description", Title = "Second" };
                var third = new TreeLeaf { Description = "Third description", Title = "Third" };
                Leaves.AddRange(new[]
                {
                    first,
                    second,
                    third,
                });
            }
        }
    }


    using System.Collections.Generic;
    
    namespace TreeViewBinding.Code
    {
        public class TreeLeaf
        {
            public TreeLeaf(TreeLeaf parent = null)
            {
                Leaves = new List<TreeLeaf>();
                Parent = parent;
            }
            public int Id { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public string Icon { get; set; }
            public List<TreeLeaf> Leaves { get; private set; }
            public TreeLeaf Parent { get; private set; }
        }
    }


    #region License
    // // Разработано: Коротенко Владимиром Николаевичем (Vladimir N. Korotenko)
    // // email: koroten@ya.ru
    // // skype:vladimir-korotenko
    // // https://vkorotenko.ru
    // // Создано:  09.05.2020 8:26
    #endregion
    
    using System.Collections.Generic;
    using System.Windows.Forms;
    using TreeViewBinding.Code;
    
    namespace TreeViewBinding
    {
        public partial class TreeViewBindingForm : Form
        {
            private TreeSource _treeSource;
            private TreeLeaf _currentLeaf;
            private TreeNode _node;
            public TreeViewBindingForm()
            {
                InitializeComponent();
                _treeSource = new TreeSource();
                _treeSource.LoadData();
                FillInTree(treeView.Nodes, _treeSource.Leaves);
            }
    
            private static void FillInTree(TreeNodeCollection  nodes, IEnumerable<TreeLeaf> leafs)
            {
                foreach (var leaf in leafs)
                {
                    var treeNode = new TreeNode(leaf.Title) {Tag = leaf};
                    nodes.Add(treeNode);
                    if (leaf.Leaves.Count > 0) FillInTree(treeNode.Nodes, leaf.Leaves);
                }
            }
    
            private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
            {
                if (e.Node.Tag is TreeLeaf item)
                {
                    _node = e.Node;
                    _currentLeaf = item;
                    titleTextBox.Text = item.Title;
                    descriptionTexBox.Text = item.Description;
                }
            }
    
            private void titleTextBox_TextChanged(object sender, System.EventArgs e)
            {
                if (_node != null)
                {
                    _currentLeaf.Title = _node.Text = titleTextBox.Text;
                }
            }
    
            private void descriptionTexBox_TextChanged(object sender, System.EventArgs e)
            {
                if (_node != null)
                {
                    _currentLeaf.Description = descriptionTexBox.Text;
                }
            }
        }
    }
    Ответ написан
    Комментировать