Why FlipView ignores SelectedItem

I would like to use FlipView to display some elements and start displaying a specific element.

To do this, I defined the class of the view model:

class MyDataContext
{

    public MyDataContext()
    {
        Items = new List<MyClass>();
        Items.Add(new MyClass("1"));
        Items.Add(new MyClass("2"));
        Items.Add(new MyClass("3"));
        SelectedItem = Items[1];
    }

    public List<MyClass> Items { get; set; }
    public MyClass SelectedItem { get; set; }
}

As you can see, the selected item is not the first item.

Now for XAML:

    <FlipView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"></FlipView>

However, when I launch the application, the flip view shows the first element, not the second element.

Is this intentional ?, or is it a mistake?

+5
source share
4 answers

try it

<FlipView
    ItemsSource="{Binding Items}"
    SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
  • your SelectedItem must be a TwoWay binding for it to work, as the value is set using both the control and the view model.
+10
source

FlipView BindableBase TwoWay. , ItemsSource, SelectedItem .

ItemSource FlipView, .

    public static List<T> ReorderList(List<T> elements, T selectedElement)
    {
        var elementIndex = elements.FindIndex(x => x.Id == selectedElement.Id);
        var result = new List<T>();

        foreach (var item in elements)
        {
            if (elementIndex .Equals(elements.Count))
            {
                elementIndex = 0;
            }

            result.Add(elements[elementIndex]);

            elementIndex++;
        }

        return result;
    }
+5

, , (MyDataContext), , . ViewModel INotifyPropertyChanged PropertyChanged

public class ViewModel : INotifyPropertyChanged
{
    private object _selectedItem;

    public object SelectedItem
    {
        get { return _selectedItem; }
        set 
        { 
            _selectedItem = value; 
            OnPropertyChanged("SelectedItem"); 
        }
    }
}

BindableBase,

public class ViewModel : BindableBase
{
    private object _selectedItem;

    public object SelectedItem
    {
        get { return this._selectedItem; }
        set { this.SetProperty(ref this._selectedItem, value); }
    }
}
+1

This seems like a mistake. If you are debugging your code, you will notice that first your SelectedItemin the virtual machine is set to the right element, then it sets the value nulland after that sets the first element of the FlipView ItemsSource item collection.

As a workaround, I see the installation of SelectedItem VM after loading the FlipView event.

0
source

All Articles