简体   繁体   English

更改treeview所选项目的属性

[英]Change property of treeview selected item

I have a treeview template like this: 我有一个像这样的treeview模板:

<HierarchicalDataTemplate DataType="{x:Type data:Category}" ItemsSource="{Binding Path=Products}">
    <TextBlock Text="{Binding Path=CategoryName}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type data:Product}">
    <StackPanel>
        <StackPanel.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Add To Project" Click="MenuItem_OnClick"/>
            </ContextMenu>
        </StackPanel.ContextMenu>
        <TextBlock Text="{Binding Path=ModelName}" />
    </StackPanel>
</HierarchicalDataTemplate>

And I am trying to add the treeview item to the linkedlist: 我正在尝试将treeview项目添加到链表:

LinkedList<Product> dll = new LinkedList<Product>();
private void MenuItem_OnClick(object sender, RoutedEventArgs e)
{
     var itemToAdd = this.tv_Project.SelectedItem as Product;
     Product previous = dll.ElementAt(dll.Count - 1);

     if(itemToAdd.CategoryID == 1)
     {
          dll.AddLast(ItemToAdd);
     }
     else if(itemToAdd.CategoryID == 2)
     {
          itemToAdd.ProductValue = previous.ProductValue + 1;
     }
     ...
}

Now when I run the above code, I found that if the previous (which I added to the linkedlist last time) and the itemToAdd (which I'm going to add to linkedlist this time) are the same, it changes the Property ProductValue of both previous and itemToAdd when this code execute: 现在,当我运行上面的代码,我发现,如果previous (我加到LinkedList的最后时间)和itemToAdd (这我要添加到LinkedList的这段时间)是相同的,它改变了物业ProductValue的执行此代码时, previousitemToAdd都将:

itemToAdd.ProductValue = previous.ProductValue + 1;

So how should I fix this? 那么我该如何解决呢? Thanks in advance! 提前致谢!

The LinkedList<T> contains references to Product objects. LinkedList<T>包含对Product对象的引用 So if two references refer to the same object, this object may be changed using any of these references. 因此,如果两个引用引用相同的对象,则可以使用这些引用中的任何一个来更改该对象。

You may want to try to add copies of products to the LinkedList<T> : 您可能想要尝试将产品的副本添加到LinkedList<T>

/* create a new Product object here and set all of its properties: */
ddl.AddLast(new Product() { Name = ItemsToAdd.Name });

You may also want to read up on how reference types work in .NET. 您可能还想阅读一下.NET中引用类型的工作方式。

And on the differences between reference and value types: 关于引用类型和值类型之间的区别:

What is the difference between a reference type and value type in c#? c#中的引用类型和值类型有什么区别?

Depending on your requirements, you may want to define Product as a value type ( struct ). 根据您的要求,您可能需要将Product定义为值类型( struct )。

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

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