gpt4 book ai didi

WPF Explorer-like MVVM ListBox-in-ListBox (master-detail) 绑定(bind)表达式

转载 作者:行者123 更新时间:2023-12-03 10:49:51 25 4
gpt4 key购买 nike

我的情况的一行总结:当我选择一个细节项目时,主人仍然没有被选中,所以我得到了错误的细节项目。

假设两个 ViewModel MasterList 和 DetailList 都是 ObservableCollection,并尝试制作类似 Explorer 的 GUI。左侧面板具有主从列表框,右侧面板将显示选定的详细信息项之一。无需在右侧面板中显示主信息。

在我的左侧面板上,ListBox 控件的编码如下。

<ListBox x:Name="listBoxMaster" ItemsSource="{Binding Path=MasterList}" SelectionMode="Extended"
IsSynchronizedWithCurrentItem="True">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBox x:Name="listBoxDetail" ItemsSource="{Binding Path=DetailList}" IsSynchronizedWithCurrentItem="True" />
</DataTemplate>
</ListBox.ItemTemplate>

请注意,我将 IsSynchronizedWithCurrentItem="True"设置为两个 ListBox 控件。

在右侧面板中,将显示所选的详细项目信息,并带有如下所示的 Binding。让我们简化名为 DetailItemClass 的详细项目类,它具有 Name 和 Number 属性。

试用1
<WrapPanel Name="wrapPanel1" DataContext="{Binding ElementName=listBoxMaster, Path=SelectedItem}">
<StackPanel DataContext="{Binding Path="DetailList/">
<TextBox Text="{Binding Path=Name}" />
<TextBox Text="{Binding Path=Number}" />
</StackPanel>
</WrapPanel>

发生了奇怪的 GUI 问题。
如果我们有。
  • Master1 有详细信息 1,2,3。
  • Master2 有细节 4,5,6。

  • 当我选择 M1-D2 时,它可以工作。
    之后,当我选择细节 M2-D4 时,它可以工作。
    但是,在那之后,当我再次选择 M1-D2 时,它不起作用!预选项目可能不会更新其要选择的主项目。
    此外,有时 M2-D5 选择会在右侧面板中给出 M1-D2。 奇怪。

    试用二
    <WrapPanel Name="wrapPanel1" DataContext="{Binding Path=MasterList/DetailList/}">
    <StackPanel>
    <TextBox Text="{Binding Path=Name}" />
    <TextBox Text="{Binding Path=Number}" />
    </StackPanel>
    </WrapPanel>

    就是不行。虽然我将 IsSynchronizedWithCurrentItem 设置为 true,但是 失败的。 我不知道为什么。

    试用3

    我只是摆脱了 DataContext XAML 绑定(bind)并在代码隐藏处使用事件触发器,如下所示。
        private void listBoxMaster_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
    if (e.AddedItems.Count == 1)
    {
    if (e.AddedItems[0] is DetailItemClass)
    {
    var element = (DetailItemClass)e.AddedItems[0];
    wrapPanel1.DataContext = element;
    }
    }
    }

    它工作得很好,但它不使用 XAML 绑定(bind)。

    你能教我正确的绑定(bind)表达吗?

    最佳答案

    你试过了吗:

    <WrapPanel Name="wrapPanel1" DataContext="{Binding ElementName=listBoxMaster, Path=SelectedItem}">
    <StackPanel>
    <TextBox Text="{Binding Path=DetailList.Name}" />
    <TextBox Text="{Binding Path=DetailList.Number}" />
    </StackPanel>
    </WrapPanel>

    或者
    <WrapPanel Name="wrapPanel1">
    <StackPanel>
    <TextBox Text="{Binding ElementName=listBoxMaster, Path=SelectedItem.DetailList.Name}" />
    <TextBox Text="{Binding ElementName=listBoxMaster, Path=SelectedItem.DetailList.Number}" />
    </StackPanel>
    </WrapPanel>

    这些是为了确保 DataContext 是否实际上是级联的。

    关于WPF Explorer-like MVVM ListBox-in-ListBox (master-detail) 绑定(bind)表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8552095/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com