简体   繁体   English

Xamarin 表单选择器绑定

[英]Xamarin Forms Picker Binding

I'd like to implement a simple picker XAML binded to 3 labels , where when I choose a value from the picker the labels will be populated automatically (the data comes from SQLite).我想实现一个绑定到3 个标签的简单选择器XAML ,当我从选择器中选择一个值时,标签将自动填充(数据来自 SQLite)。 Here is what I have:这是我所拥有的:

 <Picker x:Name="ListJobs" Title="Select Job"  ItemsSource="{Binding options}" ItemDisplayBinding="{Binding JobNo}" SelectedItem="{Binding SelectedJobs}"/>

 <Label Text="{Binding JobsId}" IsVisible="True" x:Name="TxtId"/>
 <Label Text="{Binding name}" IsVisible="True" x:Name="TxtName"/>
 <Label Text="{Binding location}" IsVisible="True" x:Name="TxtLoc"/>

Model模型

public class Jobs
{
public string JobsId {get;set;}
public string name {get;set;}
public string location {get;set;}

public Jobs(){}
}

Code Behind:代码背后:

protected override OnAppearing()
{
 jobsInfo = (List<Jobs>) GetJob();
foreach (var item in jobsInfo)
{
  Jobs options = new Jobs
{
  JobsId = item.JobsId,
  name = item.name,
  location = item.location
};
BindingContext = options;
}
}
 private IEnumerable<Jobs> GetJobsInfo()
        {
            var db = _connection.Table<Jobs>();
            return db.ToList();
        }

I would to select from picker (like dropdown) and populate the labels.我会从选择器(如下拉菜单)中选择并填充标签。

First, there are some mistakes in your code.首先,您的代码中有一些错误。

1.When you go through the loop (the data you gained from db), options is always updated with new data(so it generates using last object), and you set it to BindingContext. 1.当您通过循环(从 db 获得的数据)时,选项总是使用新数据更新(因此它使用最后一个对象生成),并将其设置为 BindingContext。 You should set a modelView here rather a model.你应该在这里设置一个模型视图而不是一个模型。

2.The itemSource of Picker must be a list , however you set a model here. 2. Picker 的 itemSource 必须是一个list ,但是你在这里设置一个模型。

3.The viewmodel must implement INotifyPropertyChanged to notify the changes. 3.viewmodel 必须实现INotifyPropertyChanged以通知更改。

I think what you need understanding most is not this Picker , it is How to work with binding.我想你最需要了解的不是这个 Picker ,而是 How to work with binding。

Bindable Properties 可绑定属性

Data Binding Basics 数据绑定基础

From Data Bindings to MVVM 从数据绑定到 MVVM

Okay, let us come back to this case.好的,让我们回到这个案例。 What you need is here你需要的就在这里

I simplified the demo and you can refer to it.我简化了demo,大家可以参考。

  • XAML XAML

     <Picker x:Name="picker" Title="Select Job" ItemsSource="{Binding JobList}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedJob}"/> <Label Text="{Binding SelectedJob.JobsId}" IsVisible="True" x:Name="TxtId" Margin="0,100,0,0"/> <Label Text="{Binding SelectedJob.Name}" IsVisible="True" x:Name="TxtName"/> <Label Text="{Binding SelectedJob.Location}" IsVisible="True" x:Name="TxtLoc"/>
  • Model and ViewModel:模型和视图模型:

     public class Jobs { public string JobsId { get; set; } public string Name { get; set; } public string Location { get; set; } } public class RootModel : INotifyPropertyChanged { List<Jobs> jobList; public List<Jobs> JobList { get { return jobList; } set { if (jobList != value) { jobList = value; OnPropertyChanged(); } } } Jobs selectedJob; public Jobs SelectedJob { get { return selectedJob; } set { if (selectedJob != value) { selectedJob = value; OnPropertyChanged(); } } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } }
  • Code behind:后面的代码:

     public MainPage() { InitializeComponent(); this.BindingContext = new RootModel { JobList = GetJobsInfo() }; } private List<Jobs> GetJobsInfo() { var db = _connection.Table<Jobs>(); return db.ToList(); }
  • My Test:我的测试:

    在此处输入图像描述

XAML: XAML:

<Picker x:Name="ListJobs" Title="Select Job" ItemsSource="{Binding AllJobs}"
        ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedJob}"/>
<Label Text="{Binding SelectedJob.JobId}" IsVisible="True" x:Name="TxtId"/>
<Label Text="{Binding SelectedJob.Name}" IsVisible="True" x:Name="TxtName"/>
<Label Text="{Binding SelectedJob.Location}" IsVisible="True" x:Name="TxtLoc"/>

Model:模型:

public class Job
{
    public string JobId { get; set; }
    public string Name { get; set; }
    public string Location {get; set; }
}

public class JobModel
{
    public List<Job> AllJobs { get; set; }
    public Job SelectedJob { get; set; }
}

Code behind:后面的代码:

protected override OnAppearing()
{
    BindingContext = new JobsModel {
        AllJobs = GetJobs()
    };
}

private List<Jobs> GetJobs()
{
    var db = _connection.Table<Jobs>();
    return db.ToList();
}
         //How to add picker or dropdownlist in Xamarin forms and bind text ?
    
    
    //we will be using Picker Properties -> pickername.ItemsSource and pickername.SelectedItem
    //In above line pickername is the x:Name given to picker 
    
    
    //page.xaml 
    
               <Frame CornerRadius="5" HeightRequest="50"  Padding="0">
                    <StackLayout Orientation="Horizontal">
                        <controls:BorderlessPicker
                                                x:Name="Pickdoctype" 
                                                ItemDisplayBinding="{Binding text}"
                                                SelectedIndexChanged="Pickdoctype_SelectedIndexChanged"
                                                HorizontalOptions="FillAndExpand"                                                                     
                                                Title="Enter Document Type"
                                                FontSize="20" 
                                                TextColor="Gray">
                        </controls:BorderlessPicker>
                        <ImageButton BackgroundColor="Transparent" Padding="0">
                            <ImageButton.Source>
                                <FontImageSource Glyph="&#xf0d7;" Size="25" 
                                                          FontFamily="{StaticResource FontAwesomeSolid}"
                                                          Color="Gray"></FontImageSource>
                            </ImageButton.Source>
                        </ImageButton>
                    </StackLayout>
                </Frame>
                
                
                
     //page.xaml.cs


      
            //Picker Get API
            var responseUserData = await httpService.Get("manageDocument/documentType/documentType/" + UserID);
            if (responseUserData.IsSuccessStatusCode)
            {
                var responseUserDataString = await responseUserData.Content.ReadAsStringAsync();
                var myDeserializedClass = JsonConvert.DeserializeObject<List<DocumentTypeModel>>(responseUserDataString);
                Pickdoctype.ItemsSource = myDeserializedClass;
               
            }
              
              
              
            //Get Picker value functionality
            private void Pickdoctype_SelectedIndexChanged(object sender, EventArgs e)
            {
                try
                {
                    DocumentTypeModel selectedItem = (DocumentTypeModel)Pickdoctype.SelectedItem;
                    string PickerValue = selectedItem.value;
                    string PickerText = selectedItem.text;
                }
                catch (Exception ex)
                {

                }
            }
    
    
    //Create a model class 
    
         public class DocumentTypeModel
        {
            public string masterName { get; set; }
            public string text { get; set; }
            public string value { get; set; }
        }
            
    

                        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM