大家晚上好,
学习 Xamarin 表单..尝试添加带有数值的选择器...(使用 https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/picker/populating-itemssource )
我已经使用此页面上的示例从 View 中填充选择器...效果很好...但是我想从后面的代码填充选择器...
<---XAML--->
<Picker Grid.Column="4" Grid.Row="2" ItemsSource="{Binding pickerSource}"/>
<---c#---->
var pickerList = new List<string>();
pickerList.Add("1");
pickerList.Add("2");
pickerList.Add("3");
pickerList.Add("4");
pickerList.Add("5");
pickerList.Add("6");
pickerList.Add("7");
pickerList.Add("8");
pickerList.Add("9");
pickerList.Add("10");
var pickerSource = new Picker { Title = "Quantity", TitleColor = Color.Red };
pickerSource.ItemsSource = pickerList;
选择器出现在应用程序上,但选择时,它没有填充任何值...为什么这个绑定(bind)不正确?
谢谢
另外...作为旁注,如果有人知道一个包含所有数值的工具,而不是我手动用 1,2,3 等填充它......
再次感谢
感谢@Jason 的回复...从这里我进行了以下操作:
---xaml--
<Picker Grid.Column="4" Grid.Row="2" ItemsSource="{Binding pickerSource}"/>
---c#----
public List<string> pickerSource { get; set; }
public void PopulateQuantityPicker()
{
var pickerList = new List<string>();
pickerList.Add("1");
pickerList.Add("2");
pickerList.Add("3");
pickerList.Add("4");
pickerList.Add("5");
pickerList.Add("6");
pickerList.Add("7");
pickerList.Add("8");
pickerList.Add("9");
pickerList.Add("10");
pickerSource = pickerList;
this.BindingContext = this;
}
选择器位于应用程序上,但未填充,它是空的。 当我点击它时,我得到以下信息:
(代码还调用了 PopulateQuantityPicker())
最佳答案
在这里,您将 ItemsSource 绑定(bind)到 pickerSource
<Picker Grid.Column="4" Grid.Row="2" ItemsSource="{Binding pickerSource}"/>
在您的代码隐藏中,您需要一个名为 pickerSource
的公共(public)属性。您只能绑定(bind)到公共(public)属性
public List<string> pickerSource { get; set }
// assign the data to your ItemsSource
pickerSource = pickerList;
// also be sure to set the BindingContext
BindingContext = this;
// this is creating a new picker named pickerSource. You have already done
// this in your XAML. This is NOT NEEDED
var pickerSource = new Picker { Title = "Quantity", TitleColor = Color.Red };
pickerSource.ItemsSource = pickerList;
如果您想在不使用绑定(bind)的情况下从后面的代码执行此操作,您首先需要为您的控件分配一个x:name
<Picker x:Name="myPicker" Grid.Column="4" Grid.Row="2" />
然后在后面的代码
myPicker.ItemsSource = pickerList;
关于c# - xamarin 形成如何从代码隐藏填充选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61014275/