共享网格视图选定项
本文关键字:视图 网格 共享 | 更新日期: 2023-09-27 18:06:30
我正在开发一个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#类:
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();
}
}
当您在网格视图中启用项目单击时,它不会导致项目被选中。这意味着imageitem.SelectedItem
属性是ShareImageHandler
中的null
。
一个简单的解决方案是更新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 ) );