簡體   English   中英

Xamarin.Forms - Picker選擇的Item綁定沒有響應

[英]Xamarin.Forms - Picker selected Item binding not responding

我制作簡單MVVM有約束力的picker中xamarin.forms領域。 我正在遵循本指南xamarin指南設置選擇器的綁定

所以我做了一個模型:

public class Operation
{
    public int Number { get; set; }
    public string Name { get; set; }
}

一個ViewModel:

private List<Operation> _operations;
public List<Operation> Operations
{
    get { return _operations; }
    set
    {
        _operations = value;
        OnPropertyChanged();
    }
}

並查看:

<Picker 
    ItemsSource="{Binding Operations}"
    ItemDisplayBinding="{Binding Number}"
    SelectedItem = "{Binding SelectedOperation}"/>
<Entry x:Name="HelpEntry"
       Text="{Binding SelectedOperation.Name}" />

在選擇器列表中,項目顯示正確,但是當我選擇項目編號時,不會顯示條目內的綁定。

Ouestion是,我做錯了什么?


順便說一句..我這樣做是因為我需要通過使用HelpEntry.Text在我的代碼隱藏部分中獲得一個選定的Operation's Name作為變量。 這不是最聰明的方式,你有更好的想法嗎?

任何幫助都會非常感激。

您的ViewModel還應包含SelectedOperation屬性,該屬性還應在其setter中調用OnPropertyChanged方法。

您還應該考慮在查看模型時使用ObservableCollection而不是List

確保ViewModel實現了INotifyPropertyChanged接口。 輕松完成此操作的方法是創建一個實現接口的BaseViewModel,然后從該基類繼承所有具體的視圖模型類。

 public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class MainPageVM : ViewModelBase
{...}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM