Xamarin-选择器所选项目未更改

时间:2018-11-28 13:44:50

标签: c# xamarin mvvm picker

我正在尝试在Xamarin中绑定选择器。

我的HTML代码

<Picker Title="Select a coin"
    ItemsSource="{Binding Coins}"
    ItemDisplayBinding="{Binding Short_Name}"
    SelectedItem="{Binding SelectedCoin,Mode=TwoWay}" />

   <Label Text="{Binding SelectedCoin.Short_Name}" /> //This does not 
   change when I change the item in the picker.

这是我在ViewModel中的代码

    public class Currency
    {
        public string Short_Name { get; set; }
        public string Image_Url { get; set; }
    }

    Currency selectedCoin;
    public ObservableCollection<Currency> _coins = new 
    ObservableCollection<Currency>();

    public Currency SelectedCoin
    {
        get { return selectedCoin; }
        set
        {
            if (selectedCoin != value)
            {
                selectedCoin = value;
                OnPropertyChanged();
            }
        }
    }

    public ObservableCollection<CryptoCurrency> Coins
    {
        get
        {
            return _coins;
        }
        set
        {
            SetObservableProperty(ref _coins, value);
        }
    }

    public async void GetCoins()
    {
        Currency c = new Currency();
        coinsPageModel.Coins = await coinsPageModel.GetCoins();

        foreach (var item in coinsPageModel.Coins)
        {
            c.Short_Name = item.Short_Name;
            Coins.Add(c);
        }
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

我尝试了几种不同的方法,但是当我更改选择器项目时,似乎似乎无法更改选择器下方标签中的文本。任何帮助或帮助,我们将不胜感激!

2 个答案:

答案 0 :(得分:0)

您应该在每次SelectedItem更改时引发属性更改,如下所示:

private ObservableCollection<Currency> _coins = new ObservableCollection<Currency>();
public ObservableCollection<CryptoCurrency> Coins
{
    get
    {
        return _coins;
    }
    set
    {
        SetObservableProperty(ref _coins, value);
    }
}

private Currency selectedCoin;
public Currency SelectedCoin
{
    get { return selectedCoin; }
    set
    {
        if (selectedCoin != value)
        {
            selectedCoin = value;
            RaisePropertyChanged(() => this.SelectedCoin);
        }
    }
}

您的XAML似乎正确。

答案 1 :(得分:0)

货币c =新的Currency(); 在GetCoins内部,应放置在foreach循环中。