编程语言
首页 > 编程语言> > c# – WinRT调用Flyout.ShowAt()async

c# – WinRT调用Flyout.ShowAt()async

作者:互联网

我正在构建我自己的Flyout控件,列表选择在Windows Phone和Windows桌面上使用它.与ListPickerFlyout类不同,Flyout类没有用于显示弹出窗口的异步方法.

如何在弹出窗口关闭后调用ShowAt方法异步并返回所选值?

解:

可以使用TaskCompletionSource< T>来实现异步行为. (感谢AwaitableUI libary).还有什么困扰我的是我必须在构造函数中手动创建ListView.如果我可以使用XAML而只是分配一个模板,那将是很好的,但我没有找到一种有效的方法.

public class ListPickerFlyout<T> : Flyout where T : class
{
    private event EventHandler<object> ItemPicked;

    public ListPickerFlyout(IEnumerable<T> items)
    {
        Placement = FlyoutPlacementMode.Full;
        Opening += OnOpening;
        Closed += OnClosed;

        var listView = new ListView();
        listView.SelectionMode = ListViewSelectionMode.None;
        listView.IsItemClickEnabled = true;
        listView.ItemClick += OnItemClick;
        listView.DisplayMemberPath = "Name";
        listView.SetBinding(ListView.ItemsSourceProperty, new Binding { Source = items });

        Content = listView;
    }

    public async Task<T> ShowAsync()
    {
        this.ShowAt(Window.Current.Content as Frame);

        var tcs = new TaskCompletionSource<T>();

        EventHandler<object> eventHandler = null;

        eventHandler = (s, e) =>
        {
            this.Closed -= eventHandler;
            this.ItemPicked -= eventHandler;

            tcs.SetResult(e as T);
        };

        this.Closed += eventHandler;
        this.ItemPicked += eventHandler;

        return await tcs.Task;
    }

    private void OnItemClick(object sender, ItemClickEventArgs e)
    {
        var selectedItem = e.ClickedItem as T;

        var eventHandler = ItemPicked;
        if (eventHandler != null)
            eventHandler(this, selectedItem);

        this.Hide();
    }

    private void OnOpening(object sender, object e)
    {
        var frame = Window.Current.Content as Frame;
        var page = frame.Content as Page;

        if (page != null)
            page.BottomAppBar.Visibility = Visibility.Collapsed;
    }

    private void OnClosed(object sender, object e)
    {
        var frame = Window.Current.Content as Frame;
        var page = frame.Content as Page;

        if (page != null)
            page.BottomAppBar.Visibility = Visibility.Visible;
    }
}

解决方法:

WinRT XAML工具包具有等待UI的概念,可以等待许多通常不应用等待逻辑的UI元素.我没有在Flyout上试过它,但它可能有效.

你可以找到它here

标签:c,async-await,windows-runtime,flyout,winrt-async
来源: https://codeday.me/bug/20190628/1315651.html