首页 文章

为什么Listbox SelectedItem返回null值?

提问于
浏览
0

我想在模型对象上创建带有 ItemsSource and SelectedItem binding 的列表框 .

绑定完成如下:

<ItemsControl ItemsSource="{Binding Persons}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Name}" Width="150" />
                    <ListBox 
                        BorderThickness="0"
                        Background="Transparent"
                        Margin="0 1"
                        ItemsSource="{Binding DataContext.Skills,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},Mode=OneWay}"
                        SelectedItem="{Binding MasterSkill, Mode=TwoWay}"
                        SelectionMode="Single"
                        ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                        >
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

在第一次加载时,使用默认的注册数据选择值 .

切换/重新加载当前viewModel UI后出现问题 . 当我回到ViewModel时,SelectItem为null .

这些值似乎在离开UI时(在卸载时)更新 . 当我使用 delay(>0) 属性或当我设置 UpdateSourceTrigger to LostFocus 时问题消失

我在Github上创建了 exemple 我的问题=> here(在例子中你必须继续"Manage Skills"窗口并切换到"Manage project"才能最终返回技能)

我认为UI线程在控件卸载或销毁时调用事件propertyChanged ...但我真的不知道如何避免这个问题 .

非常感谢你的帮助 .

1 回答

  • 0

    在您粘贴的代码中,每次单击按钮时都会创建viewmodel的新实例,这意味着将刷新现有值 . UI的情况也是如此 .

    switch (targetViewModel)
                {
                    case "1":
                        CurrentViewModel = new ProjectViewModel();
                        break;
                    case "2":
                        CurrentViewModel = new ManageSkillsViewModel();
                        break;
                    default:
                        CurrentViewModel = null;
                        break;
                }
    

    这是我正在讨论的部分 . 相反,我觉得你不需要创建这样的实例,如果你需要加载一个新的VM,你可以尝试清除现有的值 .

相关问题