Search code examples
c#wpfdata-bindingtreeview2-way-object-databinding

Binding different objects for different TreeView based on same class getting linked


I am currently having a class myCommand

class myCommand : INotifyCollectionChanged , INotifyPropertyChanged
{
    public string Name { get; set; }
    public ObservableCollection<myFile> subCommand { get; set; }
}

I have two TreeView items in my window. tvCommandList which contains all available commands and tvFinalList to hold all selected commands.

I used contextmenu to copy the items from tvCommandList to tvFinalList; In the mainWindow, I have two ObservableCollection items which are bound to the TreeViewItems.

    ObservableCollection<myCommand> cmdlist = null;
    ObservableCollection<myCommand> finallist = null;

These are bound to the TreeView in the XAML file.

<Grid>
    <Grid.Resources>
        <ResourceDictionary>
            <Style x:Key="styleTemplate" TargetType="TreeViewItem">
                <Setter Property="IsSelected" Value="{Binding IsInitiallySelected, Mode=TwoWay}" />
            </Style>
            <HierarchicalDataTemplate DataType="{x:Type data:myCommand}" 
                                      ItemsSource="{Binding subCommand, Mode=TwoWay}">
                <TextBlock Text="{Binding Name, Mode=TwoWay}" />
            </HierarchicalDataTemplate>
        </ResourceDictionary>
    </Grid.Resources>
</Grid>

<TreeView x:Name="tvSendList" ItemsSource="{Binding}" DataContext="{Binding cmdlist}">
<TreeView x:Name="tvRecvList" ItemsSource="{Binding}" DataContext="{Binding finallist}">

I copy TreeViewItem from cmdlist to finallist and edit them for customsing data. The issue I am facing here is that if I modify an item (Update the Name value) in the finallist, the cmdlist item also gets updated, which I am not sure how to go about to resolve this.

I tried moving the ResourceDictionary to each TreeView specifically, but still facing the same issue


Solution

  • You should also clone, i.e. create a copy of, each individual myFile object when you create a copy of the collection, e.g.:

    finalist = new ObservableCollection<myFile>(cmdlist.Select(x => new myFile()
    {
        Property1 = x.Property1,
        Property2 = x.Property2
        //copy all property values...
    }));