代码之家  ›  专栏  ›  技术社区  ›  John

xamarin形成了如何从代码隐藏中填充picker

  •  0
  • John  · 技术社区  · 5 年前

    晚上好,

    正在学习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等填充它,那就作为旁注。。

    再次感谢


    ---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())

    enter image description here

    0 回复  |  直到 5 年前
        1
  •  0
  •   Jason    5 年前

    您正在将ItemsSource绑定到 pickerSource

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

    在你的代码背后,你需要一个 公共财产 命名 . 你只能绑定到 公共财产

    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;
    
    推荐文章