WP8 LongListSelector SelectedItem not bindable

淺唱寂寞╮ 提交于 2019-12-20 23:24:01

问题


In WP8, they forgot to provide SelectedItem as a dependency property, hence I'm not able to bind to it. I fixed that using this: http://dotnet-redzone.blogspot.com/2012/11/windows-phone-8longlistselector.html

On doing so, I'm noticing that I'm not able to reset the property from the ViewModel, i.e. if I set the item to null in the ViewModel, it does not impact the UI. I have already provided two way binding in the UI but still setting the item to null in the ViewModel does not change the selected item in the LongListSelector. I also don't want to use the SelectionChanged event as I'm sharing ViewModels between WP7.5 app and a WP8 app, hence I want to push as much as I can into the ViewModel. Is there a solution for this?


回答1:


It appears that the custom LongListSelector class that you are using does not handle the setter properly.

Replace the OnSelectedItemChanged callback with the following:

    private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var selector = (LongListSelector)d;
        selector.SetSelectedItem(e);
    }

    private void SetSelectedItem(DependencyPropertyChangedEventArgs e)
    {
        base.SelectedItem = e.NewValue;
    }



回答2:


And there is full version of these two parts:

public class LongListSelector : Microsoft.Phone.Controls.LongListSelector
    {
        public LongListSelector()
        {
            SelectionChanged += LongListSelector_SelectionChanged;
        }

    void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        SelectedItem = base.SelectedItem;
    }

    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register(
            "SelectedItem",
            typeof(object),
            typeof(LongListSelector),
            new PropertyMetadata(null, OnSelectedItemChanged)
        );

    private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var selector = (LongListSelector)d;
        selector.SetSelectedItem(e);
    }

    private void SetSelectedItem(DependencyPropertyChangedEventArgs e)
    {
        base.SelectedItem = e.NewValue;
    }

    public new object SelectedItem
    {
        get { return GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }
}


来源:https://stackoverflow.com/questions/15232725/wp8-longlistselector-selecteditem-not-bindable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!