FlipView ContainerFromItem在SelectionChanged中返回null [英] FlipView ContainerFromItem returning null in SelectionChanged

查看:73
本文介绍了FlipView ContainerFromItem在SelectionChanged中返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在选择更改时获取FlipViewItem,因此我构建了如下代码:

I need to get the FlipViewItem when the selection changes, so I have built code like this:

<FlipView ItemsSource="{Binding Items}" SelectionChanged="FlipView_SelectionChanged_1">
    <FlipView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}"/>
        </DataTemplate>
    </FlipView.ItemTemplate>
</FlipView>



并且:

public List<string> Items { get; set; }
public MainPage()
{
    Items = new List<string>{"test", "test2", "test3", "test4"};
    this.InitializeComponent();
}
private void FlipView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    FlipView fv = sender as FlipView;
    if (fv.SelectedItem == null) return;
    var item = fv.ItemContainerGenerator.ContainerFromItem(fv.SelectedItem);
    if (item == null)
    {
        throw new InvalidOperationException("no item.  Why????");
               
    }
}

,不幸的是会抛出异常。 当所选项目发生变化时,为什么项目中没有容器? 唯一的解决方案是延迟尝试获取项目,如下所示:

and unfortunately the exception gets thrown.  Why is there no container from item when the selected item has changed?  The only solution is to delay trying to get the item, like this:

private void FlipView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    FlipView fv = sender as FlipView;
    if (fv.SelectedItem == null) return;
    var item = fv.ItemContainerGenerator.ContainerFromItem(fv.SelectedItem);
    if (item == null)
    {
        Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                var itemSecondTime = fv.ItemContainerGenerator.ContainerFromItem(fv.SelectedItem);
                if (itemSecondTime == null)
                {
                    throw new InvalidOperationException("no item.  Why????");
                }
            });
    }
}

但这感觉就像是黑客,因为我在假设系统是如何工作的,可能随时改变。 &NBSP;为什么它以这种方式表现?并且它可以被修复,以便它按照我们期望的方式工作吗?

But this feels like a hack, because I'm making assumptions about how the system is working that could change at any time.  Why is it behaving in this way? And can it be please fixed so that it works the way we would expect it to?

... Stefan

...Stefan

推荐答案

问题是否始终存在或仅在第一个 SelectionChanged事件发生?

最好的问候,

韩夏

Best Regards,
Han Xia


这篇关于FlipView ContainerFromItem在SelectionChanged中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆