【问题标题】:How to load ItemsSource before setting SelectedItem in ListView?在 ListView 中设置 SelectedItem 之前如何加载 ItemsSource?
【发布时间】:2017-04-06 02:55:53
【问题描述】:

我有一个包含ListViewMVVM 页面。我绑定了ItemSourceSelectedValue,但它第一次调用转换器为SelectedValue 然后加载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

【问题讨论】:

  • 如果我理解正确:第一次调用 IValueConverter 时,您会得到 null 传递给转换?
  • @MatthiasHerrmann :第一次调用转换器时,它会返回例如 5,但由于 ItemSource 不存在,它不会选择任何内容并且 SelectedItem 为 Null

标签: c# mvvm uwp itemssource selectedvalue


【解决方案1】:

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

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

这样你就可以代替你的输入如下,

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

这里 Model 是在您的 xaml 文件 (.cs) 的代码隐藏中定义和调用的。例如在您的 public seal partial class

之上
    public YourViewModelName Model { get; set; }

在同一个文件中public YourXamlName()

    Model = new YourViewModelName();

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

祝你好运。

【讨论】:

    猜你喜欢
    • 2011-01-18
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    相关资源
    最近更新 更多