我有一个类似的树视图模板:
<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>
我正在尝试将树视图项目添加到linkedlist:
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;
}
...
}
现在,当我运行上述代码时,我发现,如果previous
(我上次添加到LinkedList上)和itemToAdd
(这次我将添加到LinkedList)是相同的,它将更改执行该代码时,previous
和itemToAdd
的属性ProductValue
:
itemToAdd.ProductValue = previous.ProductValue + 1;
那么我应该如何解决这个问题?预先感谢!
LinkedList<T>
包含引用 to Product
对象。因此,如果两个引用是指同一对象,则可以使用以下任何引用更改此对象。
您可能想尝试将产品的副本添加到LinkedList<T>
:
/* create a new Product object here and set all of its properties: */
ddl.AddLast(new Product() { Name = ItemsToAdd.Name });
您可能还想阅读参考类型在.net中的工作方式。
以及参考和价值类型之间的差异:
C#中的参考类型和值类型之间有什么区别?
根据您的要求,您可能需要将Product
定义为值类型(struct
)。