首页 > 解决方案 > 如何在 WPF 中获取 TreeView 节点?

问题描述

我是 WPF 初学者,我有很多问题。

我做了一个TreeView程序,但我不知道如何选择一个节点。我想添加一个add和一个delete按钮。所以应该不难。

我将不胜感激任何帮助。先感谢您。

这是视图模型。它是 MVVM 模式的视图

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;

namespace TreeViewTest2
{
   public class MainViewModel : INotifyPropertyChanged
   {
       int i = 0;
       public ObservableCollection<A> a { get; set; }

       public MainViewModel()
       {
           a = new ObservableCollection<A>();
       }

       public ICommand addADelegate;
       public ICommand AddADelegate
       {
           get { return addADelegate = new delegateCommand(addA); }
       }

       public ICommand addBDelegate;
       public ICommand AddBDelegate
       {
           get { return addBDelegate = new delegateCommand(addB); }
       }

       public ICommand addCDelegate;
       public ICommand AddCDelegate
       {
           get { return addCDelegate = new delegateCommand(addC); }
       }

       public ICommand deleteADelegate;
       public ICommand DeleteADelegate
       {
           get { return deleteADelegate = new delegateCommand(deleteA); }
       }

       public ICommand deleteBDelegate;
       public ICommand DeleteBDelegate
       {
           get { return deleteBDelegate = new delegateCommand(deleteB); }
       }

       public ICommand deleteCDelegate;
       public ICommand DeleteCDelegate
       {
           get { return deleteCDelegate = new delegateCommand(deleteC); }
       }

       public void addA()
       {
           a.Add(new A { Name = "A added " + (i++) });
       }

       public void addB()
       {
           if (a.Count == 0)
           {
               MessageBox.Show(" Add A First");
           }
           else
               a[0].b.Add(new B { Name = "B added" });
       }

       public void addC()
       {
           if ( a.Count == 0 || a[0].b.Count==0 )
           {
               MessageBox.Show(" Add B First");
           }
           else
               a[0].b[0].c.Add(new C { Name = "C added" });
       }

       public void deleteA()
       {
           if (a.Count == 0)
                MessageBox.Show("Error");
           else
                a.RemoveAt(0);
       }

       public void deleteB()
       {
           if (a.Count == 0 || a[0].b.Count == 0)
                MessageBox.Show("Error");
           else
              a[0].b.RemoveAt(0);
       }

       public void deleteC()
       {
           if (a.Count == 0 || a[0].b.Count == 0 || a[0].b[0].c.Count == 0)
               MessageBox.Show("Error");
           else
               a[0].b[0].c.RemoveAt(0);
       }

       public event PropertyChangedEventHandler PropertyChanged;
       public void OnPropertyChanged(string propertyName)
       {
           if (PropertyChanged != null)
           {
               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
           }
       }
    }

    #region A
    public class A
    {
        public string Name { get; set; }             
        public ObservableCollection<B> b { get; set; }

        public A()
        {
            b = new ObservableCollection<B>();
        }
    }
    #endregion

    #region B
    public class B
    {
        public string Name { get; set; }             
        public ObservableCollection<C> c { get; set; }

        public B()
        {
            c = new ObservableCollection<C>();
        }
    }
    #endregion

    #region C
    public class C
    {
        public string Name { get; set; }
    }
    #endregion

    #region delegateCommand
    public class delegateCommand : ICommand
    {
        private Action execute;

        public delegateCommand(Action execute)
        {
            this.execute = execute;
        }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            execute?.Invoke();               
        }
    }
    #endregion    
}

这是 XAML:

<Window x:Class="TreeViewTest2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TreeViewTest2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">        
    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="6*"/>
            <ColumnDefinition Width="2*"/>
        </Grid.ColumnDefinitions>
        <TreeView Grid.Column="0" ItemsSource="{Binding a}"  >
            <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:A}" ItemsSource="{Binding b}"    >
                    <TextBlock Text="{Binding Name}"/>
                </HierarchicalDataTemplate>
                <HierarchicalDataTemplate DataType="{x:Type local:B}" ItemsSource="{Binding c}" >
                    <TextBlock Text="{Binding Name}"/>
                </HierarchicalDataTemplate>
                <DataTemplate DataType="{x:Type local:C}" >
                    <TextBlock Text="{Binding Name}" />
                </DataTemplate>
            </TreeView.Resources>
        </TreeView>
        <StackPanel Orientation="Vertical" Grid.Column="1" >
            <Button  Content="Add A" Command="{Binding AddADelegate}" />
            <Button  Content="Add B"   Command="{Binding AddBDelegate}"/>
            <Button  Content="Add C " Command="{Binding AddCDelegate}"/>
            <Button  Content="Delete A"   Command="{Binding DeleteADelegate}"/>
            <Button  Content="Delete B"   Command="{Binding DeleteBDelegate}"/>
            <Button  Content="Delete C"   Command="{Binding DeleteCDelegate}"/>
        </StackPanel>
    </Grid>
</Window>

标签: wpfmvvmtreeview

解决方案


这是我的方法

    <TreeView Background="#F8F8F8" Margin="5,16,5,0"  VerticalContentAlignment="Stretch" Grid.RowSpan="2" Name="trvActiveStructure">                
            <TreeView.Resources>                  
                <Style TargetType="TextBlock">
                    <Setter Property="Foreground" Value="Black"/>
                    <Setter Property="FontWeight" Value="Bold"/>
                </Style>
            </TreeView.Resources>
            <TreeView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <TreeViewItem ItemsSource="{Binding Productions}">                               
                                    <TreeViewItem.Header>
                                <Border CornerRadius="5" Background="{Binding BgColor}" BorderBrush="{Binding BrdColor}"
                                 BorderThickness="1">
                                    <Grid Margin="0,0,0,0">                                          
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto" MinWidth="50"></ColumnDefinition>
                                            <ColumnDefinition Width="*" MinWidth="50"></ColumnDefinition>
                                            <ColumnDefinition Width="Auto"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>
                                        <TextBlock Text="{Binding Status}" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="0"/>
                                        <TextBlock Text="{Binding Sum}" Margin="10,0,10,0" HorizontalAlignment="Left" VerticalAlignment="Center"  Grid.Column="1"/>
                                        <TextBlock Text="{Binding TotalQuantity}" HorizontalAlignment="Left"  VerticalAlignment="Center"  Grid.Column="2"/>
                                    </Grid>
                                </Border>
                            </TreeViewItem.Header>

                            <TreeViewItem.ItemTemplate>
                                <DataTemplate>
                                    <Grid Margin="0,0,0,0">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto" MinWidth="50"></ColumnDefinition>
                                            <ColumnDefinition Width="*" MinWidth="50"></ColumnDefinition>
                                            <ColumnDefinition Width="Auto"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>
                                        <TextBlock Text="{Binding Orderdescription}" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="0"/>
                                        <TextBlock Text="{Binding Quantity}" Margin="10,0,10,0" HorizontalAlignment="Left" VerticalAlignment="Center"  Grid.Column="1"/>
                                        <TextBlock Text="{Binding Shipdate}" HorizontalAlignment="Left" VerticalAlignment="Center"  Grid.Column="2"/>
                                    </Grid>
                                </DataTemplate>
                            </TreeViewItem.ItemTemplate>
                        </TreeViewItem>
                    </Grid>
                </DataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>

在 xaml.cs 中

     trvActiveStructure.ItemsSource = _product;

推荐阅读