共享gridview所选项目

时间:2016-09-10 05:17:43

标签: c# gridview uwp share

我正在开发一个UWP应用程序。在我的应用程序中有gridview,我想开发它就像有人点击gridview项目然后出现共享选项。我做了一些编码部分,但我得到零点异常。任何人都可以帮我解决这个问题...

XAML:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <GridView x:Name="gridview" ItemClick="gridviewitemclick" IsItemClickEnabled="True" >
        <GridView.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding image}" Margin="2" Height="144" Width="256"/>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</Grid>

C#class:

public sealed partial class MainPage : Page
{
    private GridView imageitem;

    public MainPage()
    {
        this.InitializeComponent();
        loaddata();

        DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
        dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.ShareImageHandler);

    }

    private void loaddata()
    {
        List<Class1> listimage = new List<Class1>
        {
            new Class1 {image="ms-appx:///images/Blo.png" },
            new Class1 {image="ms-appx:///images/Bun.png" },
            new Class1 {image="ms-appx:///images/Cght.png" },
            new Class1 {image="ms-appx:///images/rld.png" },
            new Class1 {image="ms-appx:///images/Usa.png" },
            new Class1 {image="ms-appx:///images/Wing.png" },
        };
        gridview.ItemsSource = listimage;
    }


    private async void ShareImageHandler(DataTransferManager sender, DataRequestedEventArgs e)
    {
        DataRequest request = e.Request;
        DataRequestDeferral deferral = request.GetDeferral();

        try
        {

            StorageFile imagefiles = await Package.Current.InstalledLocation.GetFileAsync(imageitem.SelectedItem.ToString());
            request.Data.SetBitmap(RandomAccessStreamReference.CreateFromFile(imagefiles));
        }
        catch
        {
            request.FailWithDisplayText("Select an image you would like to share and try again.");
        }
        finally
        {
            deferral.Complete();
        }
    }

    private void gridviewitemclick(object sender, ItemClickEventArgs e)
    {
        DataTransferManager.ShowShareUI();
    }
}

1 个答案:

答案 0 :(得分:1)

在网格视图中启用项目单击时,不会导致选择该项目。这意味着imageitem.SelectedItem内的null属性为ShareImageHandler

一个简单的解决方案是更新gridviewitemclick方法以缓存点击的项目:

private Class1 _lastClickedItem = null;

private void gridviewitemclick(object sender, ItemClickEventArgs e)
{
    _lastClickedItem = e.ClickedItem as Class1;
    DataTransferManager.ShowShareUI();
}

现在ShareImageHandler内部使用此变量来访问用户点击的项目(替换imageitem.SelectedItem引用)。您还需要使用StorageFile.GetFileFromApplicationUriAsync更改稍微检索文件的方式,因为类中的文件路径是绝对URI。

StorageFile imagefiles = 
   await StorageFile.GetFileFromApplicationUriAsync( new Uri(  _lastClickedItem.image ) );