如何在WPF中获取TreeView节点?

时间:2018-07-10 15:35:50

标签: wpf mvvm treeview

我是WPF初学者,但遇到很多问题。

我制作了一个TreeView程序,但是我不知道如何选择节点。我想添加一个add和一个delete按钮。因此,这并不困难。

我将不胜感激。预先谢谢你。

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

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>

2 个答案:

答案 0 :(得分:0)

///在您的视图内添加名称空间: xmlns:i =“ clr-amespace:System.Windows.Interactivity; assembly = System.Windows.Interactivity”

                                                                                                                                                                                                                                                                                                                                                                    

  • 为SelectedItemChangedCommand添加命令
  • 公共ICommand SelectedItemChangedCommand {get; set}
  • SelectedItemChangedCommand =新的RelayCommand(SelectedItemChangedExecute,SelectedItemChangedCanExecute);

    private void SelectedItemChangedExecute(对象参数)         {             var treeView =(TreeView)参数;             如果(treeView!= null)             {                 //在这里您可以获得选定的物品                 var selectedItem = treeView.SelectedItem;             }         }

答案 1 :(得分:0)

这是我的方法

    <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;