Xamarin Forms Picker的默认值

时间:2019-05-21 13:36:39

标签: xamarin mvvm xamarin.forms picker

我想在打开页面时获取第一个数据,但不是。我不知道我在哪里弄错了。有人可以帮忙吗?

这是我的代码;

Xaml

<Picker FontSize="15"
        SelectedItem="{Binding SelectedObject}"
        VerticalOptions="StartAndExpand"
        HorizontalOptions="FillAndExpand"
        ItemsSource="{Binding myList}"
        ItemDisplayBinding="{Binding Title}">

ViewModel


public myViewModel()
{
    GetList();
    SelectedObject = myList[0];
}



public myClass _selectedObject;

public myClass SelectedObject
{
    get
    {
        return _selectedObject;
    }
    set
    {
        _selectedObject= value;
        OnPropertyChanged("SelectedObject");

    }
}

班级

public class myClass
{
   public int ID { get; set; }

   public string Title{ get; set; }

   public string Desc{ get; set; }
}

2 个答案:

答案 0 :(得分:0)

<Picker.SelectedIndex>0</Picker.SelectedIndex>

SelectedIndex="{Binding Index}"

或交换属性顺序

<Picker FontSize="15"
    VerticalOptions="StartAndExpand"
    HorizontalOptions="FillAndExpand"
    ItemsSource="{Binding myList}"
    ItemDisplayBinding="{Binding Title}"
    SelectedItem="{Binding SelectedObject}>

答案 1 :(得分:0)

我只是编写了一个演示并使其正常运行,您可以检查它并找出出错的地方:

在后面的代码中:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();


        myViewModel vm = new myViewModel();
        this.BindingContext = vm;

        //This will also work
        //myPicker.SelectedIndex = 0;
    }
}

public class myViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public List<myClass> myList
    {
        get;
        set;
    }

    public myViewModel()
    {
        GetList();
        SelectedObject = myList[0];
    }

    public void GetList() {

        myList = new List<myClass>();

        myList.Add(new myClass(1,"firstTitle","FirstDesc"));
        myList.Add(new myClass(2, "SecondTitle", "SecondDesc"));
        myList.Add(new myClass(3, "ThirdTitle", "ThirdDesc"));

    }

    public myClass _selectedObject;


    public myClass SelectedObject
    {
        get
        {
            return _selectedObject;
        }
        set
        {
            _selectedObject = value;

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedObject"));
        }
    }
}

public class myClass
{
    public int ID { get; set; }

    public string Title { get; set; }

    public string Desc { get; set; }

    public myClass(int a , string title , string desc) {

        ID = a;
        Title = title;
        Desc = desc;
    }
}

在Xaml中:

    <!-- Place new controls here -->
<Picker x:Name="myPicker" FontSize="15"
        BackgroundColor="Red"
    VerticalOptions="CenterAndExpand"
    HorizontalOptions="CenterAndExpand"
    ItemsSource="{Binding myList}"
    ItemDisplayBinding="{Binding Title}"
    SelectedItem="{Binding SelectedObject}"
        />

我上传了示例here。让我知道它是否有效。