簡體   English   中英

Xamarin Forms 中的選取器選定值

[英]Picker Selected Value in Xamarin Forms

我在 Xamarin Forms 有一個選擇器,其國家信息如下:

picker.ItemSource = countryInfo;  //(its working perfectly)

結果:

(+1) United States
(+971) United Arab Emirates
(+27)  South Africa

現在因為picker綁定了這個字符串,它是代碼和名稱的組合,所以我很難將picker.SelectedItem設置為+971。 在選定的項目中,我不需要國名。 任何提示或提示或幫助將非常有義務?

在此處輸入圖像描述 在此處輸入圖像描述

我這里只需要+355。 如果有人經歷過同樣的事情或對此有任何想法,請提供幫助。

string jsonFileName = "CountryCodes.json";
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
List<Country> countryList = new List<Country>();
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
using (var reader = new StreamReader(stream))
{
    var jsonString = reader.ReadToEnd();
    countryList = JsonConvert.DeserializeObject<List<Country>>(jsonString);
    var countryInfo = countryList as List<Country>;
    picker.ItemsSource = countryInfo.Select(code => code.pickerListEn).ToList();
}

用戶將 select (+355) Algeria 但我需要顯示的所選項目是 +355 不是所選項目部分的 rest

如果你想在列表中顯示 '(' + Code + ')' + Country Name,並在選擇器文本中顯示 + Code,我建議你可以使用 Picker 自定義渲染來渲染選擇器對話框。

我建議你可以使用綁定到這個,我創建新的 class 就像你的國家 class。

 public class Country
{
    //there may have other properties
    public string Id { get; set; }
    public string pickerListEn { get; set; }
}

然后創建 List,在此列表中添加項目,將此列表綁定到 Picker.ItemsSource

 public partial class Page1 : ContentPage, INotifyPropertyChanged
{
    private List<Country> _countryInfo;
    public List<Country> countryInfo
    {
        get { return _countryInfo; }
        set
        {
            _countryInfo = value;
            RaisePropertyChanged("countryInfo");
        }
    }     

        this.BindingContext = this;

    }

    public event PropertyChangedEventHandler PropertyChanged;      
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

在 PCL 中創建 CustomPicker class:

  public  class CustomPicker: Picker
{

}

Android 中的渲染選擇器:

[assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerAndroid))]

命名空間 PickerSample.Droid { public class CustomPickerAndroid: PickerRenderer { 私人對話框;
公共 CustomPickerAndroid() {

    }
    private string title;
    private BindingBase displayText;
    protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
    {
        base.OnElementChanged(e);
        Control.Click += Control_Click;

        var customPicker = (e.NewElement != null) ? (CustomPicker)e.NewElement
            : (e.OldElement != null) ? (CustomPicker)e.OldElement
            : new CustomPicker();

        title = !string.IsNullOrWhiteSpace(customPicker.Title)? customPicker.Title : "Select an item";
        displayText = customPicker.ItemDisplayBinding;



    }
    protected override void Dispose(bool disposing)
    {
        Control.Click -= Control_Click;
        base.Dispose(disposing);
    }



    private void Control_Click(object sender, EventArgs e)
    {
        var model = Element;
        dialog = new Dialog(Forms.Context);
        dialog.SetContentView(Resource.Layout.custom_picker_dialog);
        var textView = (TextView)dialog.FindViewById(Resource.Id.titletextview);
        textView.Text = title;
        //textView.SetTextColor(titleColor);
        var items = new List<object>();
        foreach (var item in model.ItemsSource)
            items.Add(item);
        var listView = (Android.Widget.ListView)dialog.FindViewById(Resource.Id.listview);
        listView.Adapter = new MyAdapter(items, displayText);

        listView.ItemClick += (object sender1, AdapterView.ItemClickEventArgs e1) =>
        {
            Element.SelectedIndex = e1.Position;

            dialog.Hide();
            var obj = items[e1.Position];
           string mDisplay = ((Binding)displayText).Path;
            string value1 = obj.GetType().GetProperty(mDisplay).GetValue(obj, null).ToString();
            string code = (value1.Split(new char[] { ' ' }))[0];
            code = code.Substring(1, code.Length - 2);
            Control.Text = code;
        };
        if (model.ItemsSource.Count > 3)
        {
            var height = Xamarin.Forms.Application.Current.MainPage.Height;
            var width = Xamarin.Forms.Application.Current.MainPage.Width;
            dialog.Window.SetLayout(700, 800);
        }
        dialog.Show();
    }



    class MyAdapter : BaseAdapter
    {
        private IList<object> mList;

        private Android.Graphics.Color mColor;
        private string mDisplay;
        public MyAdapter(IList<object> itemsSource, BindingBase display)

        {
            mList = itemsSource;                              
            mDisplay = ((Binding)display).Path;
        }
        public override int Count => mList.Count;
        public override Java.Lang.Object GetItem(int position)
        {
            var myObj = mList.ElementAt(position);
            return new JavaObjectWrapper<object>() { Obj = myObj };
        }
        public override long GetItemId(int position)
        {
            return position;
        }
        public override Android.Views.View GetView(int position, Android.Views.View view, ViewGroup parent)
        {
            view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.cell_layout, null);

            var text = view.FindViewById<TextView>(Resource.Id.textview1);

            var obj = mList.ElementAt(position);
            //string value1 = obj.GetType().GetProperty(mDisplay).GetValue(obj, null).ToString();
            //string code = (value1.Split(new char[] { ' ' }))[0];
            //code = code.Substring(1, code.Length - 2);
            text.Text = obj.GetType().GetProperty(mDisplay).GetValue(obj, null).ToString();

            return view;
        }
    }
    public class JavaObjectWrapper<T> : Java.Lang.Object
    {
        public T Obj { get; set; }
    }
}

}

在 layout 文件夾(在 Resources 中)添加一個名為 cell_layout.axml 的 Android Layout,它定義了 Picker 的每個元素的外觀。

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

    android:id="@+id/textview1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="fill"/>
</LinearLayout>

In the same folder add another Android Layout called custom_picker_dialog.xml, which contains a TextView and a ListView inside a LinearLayout that will be used to implement the interface (and later, the functionality) of a Xamarin.Forms Picker.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
 android:gravity="fill">
<TextView
    android:id="@+id/titletextview"
    android:layout_width="200dp"
    android:layout_height="25dp"
    android:paddingLeft="25dp"
    android:paddingRight="25dp"/>

  <ListView
    android:id="@+id/listview"
    android:layout_gravity="center"

    android:layout_width="match_parent"
    android:dividerHeight="3dp"
    android:layout_height="0dp"
    android:layout_weight="1"/>
</LinearLayout>

截圖:

在此處輸入圖像描述

我在github提供了一個樣品,你可以看看;

https://github.com/CherryBu/Pickersample

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM