xamarin 形成如何从后面的代码填充选择器

xamarin forms how to populate picker from code behind

晚安,

学习 Xamarin 表单..正在尝试添加带有数值的选择器...(使用 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/picker/populating-itemssource

我已经使用此页面上的示例从视图中填充选择器...工作正常...但是我想从后面的代码填充选择器...

<---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;

选择器出现在应用程序上,但是当被选中时,它没有填充任何值...为什么这个绑定不正确?

谢谢

此外...作为旁注,如果有人知道包含所有数值的工具,而不是我必须手动填充 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 绑定到 pickerSource

<Picker Grid.Column="4"  Grid.Row="2" ItemsSource="{Binding pickerSource}"/>

在你后面的代码中,你需要一个名为 pickerSourcepublic 属性。您只能绑定到 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;

如果你想在不使用绑定的情况下从后面的代码中执行此操作,你首先需要为你的控件分配一个 x:name

<Picker x:Name="myPicker" Grid.Column="4"  Grid.Row="2" />

然后在后面的代码中

myPicker.ItemsSource = pickerList;