【问题标题】:Binding different objects for different TreeView based on same class getting linked基于相同的类为不同的TreeView绑定不同的对象被链接
【发布时间】:2020-07-29 04:38:16
【问题描述】:

我目前有一个class myCommand

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

我的窗口中有两个 TreeView 项目。 tvCommandList 包含所有可用的命令和 tvFinalList 保存所有选定的命令。

我使用上下文菜单将项目从 tvCommandList 复制到 tvFinalList; 在主窗口中,我有两个绑定到 TreeViewItems 的 ObservableCollection 项。

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

这些绑定到 XAML 文件中的 TreeView。

<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}">

我将 TreeViewItem 从 cmdlist 复制到 finallist 并编辑它们以获取海关数据。 我在这里面临的问题是,如果我修改 finallist 中的项目(更新 Name 值),cmdlist 项目也会更新, 哪一个 我不确定如何解决这个问题。

我尝试将 ResourceDictionary 移动到每个 TreeView,但仍然面临同样的问题

【问题讨论】:

    标签: c# wpf data-binding treeview 2-way-object-databinding


    【解决方案1】:

    当您创建集合的副本时,您还应该克隆,即创建每个单独的 myFile 对象的副本,例如:

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

    【讨论】:

    • 谢谢。这为我解决了这个问题。在附加到第二个集合时克隆每个对象解决了这个问题。!!
    猜你喜欢
    • 2018-01-17
    • 1970-01-01
    • 2013-12-24
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多