簡體   English   中英

Xamarin 表單選擇器綁定

[英]Xamarin Forms Picker Binding

我想實現一個綁定到3 個標簽的簡單選擇器XAML ,當我從選擇器中選擇一個值時,標簽將自動填充(數據來自 SQLite)。 這是我所擁有的:

 <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"/>

模型

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

public Jobs(){}
}

代碼背后:

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

我會從選擇器(如下拉菜單)中選擇並填充標簽。

首先,您的代碼中有一些錯誤。

1.當您通過循環(從 db 獲得的數據)時,選項總是使用新數據更新(因此它使用最后一個對象生成),並將其設置為 BindingContext。 你應該在這里設置一個模型視圖而不是一個模型。

2. Picker 的 itemSource 必須是一個list ,但是你在這里設置一個模型。

3.viewmodel 必須實現INotifyPropertyChanged以通知更改。

我想你最需要了解的不是這個 Picker ,而是 How to work with binding。

可綁定屬性

數據綁定基礎

從數據綁定到 MVVM

好的,讓我們回到這個案例。 你需要的就在這里

我簡化了demo,大家可以參考。

  • 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"/>
  • 模型和視圖模型:

     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)); } } }
  • 后面的代碼:

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

    在此處輸入圖像描述

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"/>

模型:

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

后面的代碼:

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