首页 > 解决方案 > 当 ViewModel Xamarin.Forms 中的值更改时,选取器 SelectedItem 未更新

问题描述

我有 ViewModel 应该根据数据库中的数据更新 View 的 UI 控件。这发生在正确更新条目控件但即使参数更改 ViewModel 中的值时我的选择器也没有得到更新的选择。

以下是 View 的 Xaml 中的一些代码:

<Entry x:Name="TitleBox" Grid.Row="0" HorizontalOptions="FillAndExpand" Placeholder="Title" Text="{Binding Title, Mode=TwoWay}"/>
<Picker x:Name="TypeCombo" Title="Type" Grid.Row="2" SelectedItem="{Binding Type, Mode=TwoWay}" ItemsSource="{Binding FeaturedType}"/>

和视图模型:

    public string Title
        {
            get => _Version.Title;
            set
            {
                if (_Version.Title != value)
                {
                    _Version.Title = value;
                    NotifyPropertyChanged("Title");
                }
            }
        }

    public string Type
        {
            get => _Version.Type;
            set
            {
                if (_Version.Type != value)
                {
                    _Version.Type = value;
                    NotifyPropertyChanged("Type");
                }
            }
        }

    #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion

在 ViewModel 中的某个时刻,_Version 被分配了一个来自 DB 的对象,并且相应地分配了它的 Title 和 Type。

当页面完成加载时,我的 UI 会更新标题,但即使 ViewModel 中的值正确,也不会选择 Picker 中的类型。Picker 保持在 -1 (虽然源项是正确的):

ObservableCollection<string> _featuredType;
    public ObservableCollection<string> FeaturedType
    {
        get => _featuredType;
        set
        {
            if (_featuredType != value)
            {
                _featuredType = value;
                NotifyPropertyChanged("FeaturedType");
            }
        }
    }

我在这里迷失了方向,因为 UWP 中的 ComboBox 等效项可以正常工作,但我不得不转向 Xamarin,因为我越来越依赖 Android。

这就是我绑定到 ViewModel 的方式:

public PageViewModel ViewModel { get; set; }
BindingContext = this.ViewModel = new PageViewModel();

另外,我注意到在后面的代码中做一些测试,如下所示:

            string testType = ViewModel.Type;
            string testTitle = ViewModel.Title;

返回正确的 Title 值,但 Type 值导致 Null,即使在 ViewModel 中它是正确的。

标签: xamarin.formsbindingviewmodelselecteditempicker

解决方案


好的,我找到了解决方案,但是我不确定为什么我以前的解决方案不起作用。

@Sparsha Bhattarai 让我朝着正确的方向前进,基本上是为了避免订单问题,我从 Xaml 中填充 ItemsSource 而不是 ViewModel 中的代码,如下所示:

<Picker.ItemsSource>
    <x:Array Type="{x:Type x:String}">
        <x:String>Type1</x:String>
        <x:String>Type2</x:String>
        <x:String>Type3</x:String>
    </x:Array>
</Picker.ItemsSource>

这解决了我的问题,并且 Pickers 正在从 ViewModel 获取正确的 SelectedItem。

但是,如果我不知道 Source 中有哪些可用的项目,这将无济于事。幸运的是,在这种特殊情况下,我可以预先定义选择器项目。但是,我想知道为什么它不适用于 viewmodel 中的代码。


推荐阅读