[英]how to set value to picker in xamarin forms
你好,我正在研究 xamarin 表單 3.0 項目,我正在使用選擇器來選擇值,並使用相同的方法向選擇器顯示用戶數據。 現在我的問題是我無法將用戶從數據庫中選擇的值顯示給選擇器。請幫助...
背后的代碼
下面是我將數據傳遞到此頁面的頁面構造函數
public SummaryDetail(CpDetails cp)
{
InitializeComponent();
if (cp == null)
{
throw new System.ArgumentNullException(nameof(cp));
}
GetLocations();
BindingContext = cp;
pklocation.SelectedIndex = cp.LocationId;
}
public async void GetLocations()
{
var loci = new List<Locations>();
var client = new HttpClient();
var json = await client.GetStringAsync("this is the link from where i am getting other values in picker");
loci = JsonConvert.DeserializeObject<List<Locations>>(json);
pklocation.ItemsSource = loci;
}
<Picker x:Name="pklocation" Title="Select Location" ItemDisplayBinding="{Binding Name}"/>
pklocation.SelectedIndex = cp.LocationId;
這似乎不正確。
SelectedIndex
表示ItemsSource
集合中的索引。 它並不神奇地知道要選擇哪個 Id。 因此,您需要找出列表中所選對象的索引並將SelectedIndex
設置為該索引。 但可能更容易的是設置SelectedItem
: pklocation.SelectedItem = cp;
如果這不起作用,請嘗試以下操作:
pklocation.SelectedItem = ((List<Locations>)pklocation.ItemsSource).FirstOrDefault(c => c.LocationId == cp.LocationId);
盡管如此,我還是建議在更全局的級別上保存loci
變量,以便您可以從GetLocations
方法中引用它。
有關 Microsoft Docs 的更多信息: https : //docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/picker/
謝謝@Gerald Versluis 的幫助,但我已經通過使用數組添加項目來完成它,然后我通過比較 GetLocation() 本身中的索引將 SelectedIndex 設置為選定的值,如下所示......
private int selectedLocation;
public SummaryDetail(CpDetails cp)
{
InitializeComponent();
GetLocations();
BindingContext = cp;
selectedLocation = cp.LocationId;
}
public async void GetLocations()
{
var loci = new List<Locations>();
var client = new HttpClient();
var json = await client.GetStringAsync("this is link");
loci = JsonConvert.DeserializeObject<List<Locations>>(json);
foreach (var item in loci)
{
pklocation.Items.Add(item.Name);
if (item.Id == selectedLoacion)
pklocation.SelectedIndex = item.Id;
}
}
對我來說,綁定到 ViewModel 像這樣工作正常。
XAML
<Picker x:Name="gender" Title="Select Gender" TitleColor="Blue" SelectedItem="{Binding Gender}">
視圖模型代碼
public Object _gender;
public Object Gender
{
get { return _gender; }
set
{
_gender = value;
OnPropertyChanged();
}
}
在從數據庫中檢索數據的函數內
Gender = (string)profile["gender"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.