如何在 ListView 中设置 SelectedItem 之前加载 ItemsSource? [英] How to load ItemsSource before setting SelectedItem in ListView?

查看:21
本文介绍了如何在 ListView 中设置 SelectedItem 之前加载 ItemsSource?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MVVM 页面,其中包含一个 ListView.我绑定了 ItemSourceSelectedValue,但是它第一次调用 SelectedValue 的转换器然后加载 ItemSource.

I have a MVVM page that contains a ListView. I bind ItemSource and SelectedValue, but first time it calls converter for SelectedValue then loads ItemSource.

<ListView x:Name="ListViewSurahs"  
              ItemsSource="{Binding MyItems}"
              FlowDirection="LeftToRight"
              Grid.Column="2"
              Grid.Row="4"
              VerticalAlignment="Top"
              HorizontalAlignment="Left"
              HorizontalContentAlignment="Center"
              SelectionMode="Single"
              ScrollViewer.VerticalScrollBarVisibility="Auto"
              DisplayMemberPath="Name"
              SelectedValuePath="ID"
              SelectedValue="{Binding Source={StaticResource CurrentInfo},
                                      Path=Instance.ID,Mode=OneWay}"
              ShowsScrollingPlaceholders="False" />

因为我丢失了 SelectedItem 并且没有项目被选中.我应该怎么做才能先加载 ItemsSource?

because of that I lose SelectedItem and no Items get selected. what should I do to load ItemsSource first?

推荐答案

首先,您可以尝试在代码隐藏中键入您的 ItemsSource.您必须在 xaml 文件中添加 UserLoaded 属性才能执行此操作.但也许我们需要查看您的代码隐藏和视图模型.无论如何,您应该尝试将您的 SelectedValue 绑定模式 OneWay 更改为 TwoWay.

Firstly you can try to type your ItemsSource in codebehind. You have to add an UserLoaded property in your xaml file to do this. But maybe we need to see your codebehind and viewmodel. Anyway you should try to change your SelectedValue binding mode OneWay to the TwoWay.

之后你应该注意你的装订风格.您必须在 viewmodel 中完成大部分开发进度,然后您可以使用 get-set 从您的 xaml 代码隐藏 (.cs) 中调用您的视图模型.因此,您将拥有一个非常干净的绑定结构.

After that you should watch your binding style. You have to complete most of your development progress in your viewmodel, and after that you could just call your viewmodel from your xaml codebehind (.cs) with get-set. So, you will have a very clean binding structure.

这样你就可以用下面的方式代替你的了,

In this way you can type as follows instead of yours,

    SelectedValue="{Binding Model.BlaBla, Mode=TwoWay}"

在这里模型是在你的xaml文件(.cs)的代码隐藏中定义和调用的.例如在您的公共密封部分类

in here Model is defined and called in your codebehind of xaml file (.cs). For example in top of your public sealed partial class

    public YourViewModelName Model { get; set; }

并且在同一个文件中 public YourXamlName()

    Model = new YourViewModelName();

这是一个快速的答案,我不确定.但你应该试一试.

It is a quickly answer and I am not sure. But you should give a shot.

祝你好运.

这篇关于如何在 ListView 中设置 SelectedItem 之前加载 ItemsSource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆