繁体   English   中英

如何为每个TreeViewItem设置事件?

[英]How to set event for every TreeViewItem?

我想为我在代码中动态创建的每个TreeViewItem设置一个事件。 我正在使用以下XAML代码:

<Window.Resources>
        <Style TargetType="TreeViewItem">
            <EventSetter Event="Selected" Handler="TreeViewItemSelectionEvent"/>
            <EventSetter Event="MouseRightButtonDown" Handler="TreeViewItemRightClickEvent"/>
        </Style>
</Window.Resources>

但这仅适用于TreeView中的根TreeViewItem。 如果我单击另一个项目,它是根的子级,那么我总是返回根。

我可以以某种方式进行这项工作吗? 我很喜欢这种方法,因此您无需处理代码中的事件,从而使它看起来更干净。

TL; DR:使用HierarchicalDataTemplate和样式在TreeView中显示数据。 在视图模型中动态加载数据将自动更新TreeView。

不要手动创建TreeViewItems。

在MVVM中,最重要的是数据和数据的体系结构。 通常的模式是定义数据,并分别定义视图如何显示数据。 您的视图取决于数据,而不是相反。

因此,让我们创建一个ProductViewModel ,它具有一个ProductName ,一个子产品列表和一个IsSelected属性。 我们为此类配备了方法LoadSubProductsCollectionFromDataSource ,该方法可从您可能拥有的任何数据源中检索数据。 在这里,我只加载一些虚拟物品。

public class ProductViewModel {
    /// <summary>
    /// Backing field for the IsSelected property
    /// </summary>
    private bool _isSelected;

    /// <summary>
    /// Gets or sets the collection of materials used to build this Product.
    /// </summary>
    public ObservableCollection<ProductViewModel> SubProducts { get; set; } = new ObservableCollection<ProductViewModel>();

    /// <summary>
    /// Gets or sets the name of this product.
    /// </summary>
    public string ProductName { get; set; }

    /// <summary>
    /// Gets or sets the selected state of this product.
    /// </summary>
    public bool IsSelected {
        get => _isSelected;
        set {
            //The product has been selected or deselected.
            if (!_isSelected && SubProducts.Count == 0) {
                //We load data into it if not already done.
                LoadSubProductsCollectionFromDataSource();
            }
            _isSelected = value;
        }
    }

    /// <summary>
    /// Loads sub products data into this product.
    /// </summary>
    private void LoadSubProductsCollectionFromDataSource() {
        //..
        //Do stuff to retrieve your data dynamically and
        //add them to the SubProducts collection.
        //...
        for (int i = 0; i < 5; i++) {
            //Add dummy items
            SubProducts.Add(new ProductViewModel() { ProductName = "Some product " + i.ToString() });
        }
    }
}

在您的MainWindow.xaml.cs中,初始化并公开如下所示的视图模型对象的集合:

public partial class MainWindow : Window {
    /// <summary>
    /// Exposes the root product of the tree
    /// </summary>
    public ObservableCollection<ProductViewModel> RootProducts { get; } = new ObservableCollection<ProductViewModel>();

    public MainWindow() {
        InitializeComponent();
        RootProducts.Add(new ProductViewModel() { ProductName = "Root product" });
    }
}

该集合通常将存储在主viewmodel对象中,但为简单起见,我只是在MainWindow中创建了它。 请注意,我是如何将其作为属性(允许绑定)和ObservableCollection(在集合更改时自动通知视图)公开的。

最后,告诉您的视图如何使用TreeView显示ProductViewModel对象:

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        x:Name="window"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <!--Tell the treeview how to hierarchically display and organize ProductViewModel items-->
        <HierarchicalDataTemplate DataType="{x:Type local:ProductViewModel}" ItemsSource="{Binding SubProducts}">
            <TextBlock Text="{Binding ProductName}"></TextBlock>
        </HierarchicalDataTemplate>
        <!--Tell each treeviewitem to bind IsSelected to the PoductViewModel.ISSelected property.-->
        <Style TargetType="TreeViewItem">
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"></Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <TreeView ItemsSource="{Binding ElementName=window, Path=RootProducts}"/>
    </Grid>
</Window>

现在,每次在TreeViewItem中选择TreeView ,其IsSelected属性都设置为true(这是TreeViewItem的行为)。 由于我们的绑定,它还将相应ProductViewModelIsSelected属性设置为true。 在此属性的设置器中,我们进行了调用以填充子产品列表。 因为此列表实际上是一个ObservableCollection ,所以它通知View( TreeView ),后者知道应该使用新的TreeViewItems更新自身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM