繁体   English   中英

Xamarin 选择器绑定

[英]Xamarin Picker binding

我是否遗漏了某些东西,或者还有更多我没有得到的东西? 我正在开发一个移动应用程序,并且必须使用选择器从数据表中进行选择。 首先,我有许多基于键/值的选择器。 我有一个内部 ID 和相应的 Show 值。 ID 并不总是具有 1、2、3 值,例如源自查找表,并且可能具有以下内容

KeyID / ShowValue
27 = Another Thing
55 = Many More
12 = Some Item

检索起来很简单

select * from LookupTable where Category = 'demo'

所以我在下面有这个类,用于通过记录列表绑定选择器

public class CboIntKeyValue
{
    public int KeyID { get; set; } = 0;
    public string ShowValue { get; set; } = "";
}

现在,我尝试绑定的数据记录只有与查找关联的 ID 列。 无需陷入XAML中,但总的来说,我有我的 ViewModel。 在这上面,我有一个包含 ID 列的数据记录实例。

public class MyViewModel : BindableObject
{
    public MyViewModel()
    {
        // Sample to pre-load list of records from data server of KVP
        PickerChoices = GetDataFromServerForDemo( "select * from LookupTable where Category = 'demo'" );


        ShowThisRecord = new MyDataRec();
        // for grins, I am setting the value that SHOULD be defaulted
        // in picker.  In this case, ID = 12 = "Some Item" from above
        ShowThisRecord.MyID = 12;
    }

    // this is the record that has the "ID" column I am trying to bind to
    public MyDataRec ShowThisRecord {get; set;}

    // The picker is bound to this list of possible choices
    public List<CboIntKeyValue> PickerChoices {get; set;}
}

我无法绑定到列表的索引,因为当我期望相应的“ID”成为列表中正确记录的基础时,这会给我 0、1、2。

在 WPF 中,我过去能够为屏幕声明显示值,也可以将值绑定到类似的 ID 列。 因此,我的“ShowThisRecord”上的 INT 属性的绑定将驱动并正确刷新。

我可以看到 SelectedItem 的绑定,但这是 KVP 类的整个项目,它不是MyDataRec 的一部分。 只有 ID 是它们之间的共同元素。

什么是让它工作的正确绑定?

<Picker ItemDisplayBinding="{Binding ShowValue}"
   SelectedItem="{Binding ???}" />

只是为了确认我的记录绑定是合法的,我的页面具有与 MyViewModel 的绑定上下文,因为我可以通过我添加到页面的示例文本条目正确地查看 ID。

<Entry Text="{Binding Path=ShowThisRecord.MyID}"/>

我创建了一个演示来测试您的代码,它可以正常工作。 完整的演示在这里 我还添加了一个功能来验证所选项目。

如果你想同步获取SelectedItem对象,MyViewModel 应该实现INotifyPropertyChanged ,我为SelectedItem创建了一个selectedRecord字段,所以你可以这样做:

public class MyViewModel : ViewModelBase
{
    public MyViewModel()
    {
        // Sample to pre-load list of records from data server of KVP
        //PickerChoices = GetDataFromServerForDemo("select * from LookupTable where Category = 'demo'");
        PickerChoices = new ObservableCollection<TestModel>() {
            new TestModel{MyID = 5, ShowValue="test1"}, new TestModel{MyID = 9, ShowValue="test2"},
            new TestModel{MyID = 18, ShowValue="test18"}, new TestModel{MyID = 34, ShowValue="test4"}
        };
        // Set the default selected item
        // foreach (TestModel model in PickerChoices) {
        //     if (model.MyID == 18) { // Default value
        //         SelectedRecord = model;
        //         break;
        //     }
        // }

        ShowThisRecord = new TestModel();
        // For grins, I am setting the value that SHOULD be defaulted
        // in picker.  In this case, ID = 12 = "Some Item" from above
        ShowThisRecord.MyID = 12;
    }

    // This is the record that has the "ID" column I am trying to bind to
    public TestModel ShowThisRecord { get; set; }

    //*****************************************

    TestModel selectedRecord; // Selected item object
    public TestModel SelectedRecord
    {
        get { return selectedRecord; }
        set
        {
            if (selectedRecord != value)
            {
                selectedRecord = value;
                OnPropertyChanged();
            }
        }
    }

    //*****************************************

    // The picker is bound to this list of possible choices
    public ObservableCollection<TestModel> PickerChoices { get; set; }
}

ViewModelBase

 public  class ViewModelBase: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

XAML 内容:

 <Picker Title="Select a value" x:Name="mypicker"
    ItemsSource="{Binding Path= PickerChoices}"
    SelectedItem="{Binding SelectedRecord}"
    ItemDisplayBinding="{Binding MyID}"/>

文件xaml.cs

public partial class MainPage : ContentPage
{
    ObservableCollection<TestModel> items = new ObservableCollection<TestModel>();
    MyViewModel testModel = null;
    public MainPage()
    {
        InitializeComponent();

        testModel = new MyViewModel();
        BindingContext = testModel;

        // This will also work
        //if (testModel!=null && testModel.PickerChoices!=null) {
        //  for (int index=0; index< testModel.PickerChoices.Count; index++) {
        //      TestModel temp = testModel.PickerChoices[index];
        //      if (18 == temp.MyID) {
        //          mypicker.SelectedIndex = index;
        //          break;
        //      }
        //  }
        //}

        foreach (TestModel model in testModel.PickerChoices)
        {
            if (model.MyID == 18)
            { // Default value
                testModel.SelectedRecord = model;
                break;
            }
        }
    }


    // To show the selected item
    private void Button_Clicked(object sender, EventArgs e)
    {
        if (testModel.SelectedRecord!=null) {
            DisplayAlert("Alert", "selected Item  MyID: " + testModel.SelectedRecord.MyID + "<--> ShowValue: " + testModel.SelectedRecord.ShowValue, "OK");
        }
    }

}

结果是:

在此处输入图像描述

您需要将 ItemsSource 属性设置为您的 CboIntValue 项目列表:

<Picker Title="Select a value"
        ItemsSource="{Binding PickerChoices}"
        ItemDisplayBinding="{Binding ShowValue}" />

经过大量工作,我最终为我需要的东西编写了自己的单独的类和模板样式。 由于它的长度,以及发布源代码供任何人使用、审查、评估等等,我将其发布在 The Code Project 上

同样,我遇到的主要问题是,如果我有一个来自数据源的整数键 ID,则选择器不会仅通过给定的 ID(int 或字符串)自动刷新自身。

暂无
暂无

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

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