我有一个UWP UI,它包含一个GridView并且不使用Xaml。我想显示完整的代码隐藏构造项目。没有Xaml模板。
我发现GridView的ChoosingItemContainer事件将允许我以编程方式创建GridViewItem实例,甚至可能重用它们。
但是,项目的自定义用户界面并未实际显示。
我注意到,滚动大量数据时,内容显示非常简短,然后消失。我猜测GridViewItem的内容正在被某种默认模板覆盖。有没有办法禁用这个机器?
更一般地说,有没有一种已知的方式来使用没有Xaml的GridView + Items?
UPDATE:
下面是一个说明该问题的最小代码示例。 将CustomGridView放置在用户界面的某个位置。
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
namespace MyApp
{
// Some kind of data object
public class MyData
{
public string MyProperty;
}
// A custom GridViewItem
public class MyGridViewItem : GridViewItem
{
private TextBox mTextBox;
public MyGridViewItem()
{
mTextBox = new TextBox();
mTextBox.Width = 100;
mTextBox.Height = 100;
Content = mTextBox;
// Make the items visible at all: use red background
Background = new SolidColorBrush(Color.FromArgb(255,255,0,0));
}
public void SetData(MyData d)
{
mTextBox.Text = d.MyProperty;
// Content seems to be always reset to the data object itself.
Content = mTextBox;
// With the following line the contents appear briefly while the view is scrolling.
// Without this line the contents don't appear at all
Template = null;
}
}
// Custom grid. No Xaml.
public class CustomGridView : GridView
{
public CustomGridView()
{
this.ChoosingItemContainer += CustomGridView_ChoosingItemContainer;
// Create some data to show.
CollectionViewSource s = new CollectionViewSource();
ObservableCollection<MyData> oc = new ObservableCollection<MyData>();
for(int i = 0;i < 10000;i++)
{
MyData d = new MyData();
d.MyProperty = i.ToString();
oc.Add(d);
}
s.Source = oc;
ItemsSource = s.View;
}
private void CustomGridView_ChoosingItemContainer(ListViewBase sender,ChoosingItemContainerEventArgs args)
{
// Unchecked cast, but for the sake of simplicity let's assume it always works.
MyData d = (MyData)args.Item;
MyGridViewItem it = null;
if((args.ItemContainer != null) && (args.ItemContainer.GetType() == typeof(MyGridViewItem)))
it = (MyGridViewItem)args.ItemContainer;
else
it = new MyGridViewItem();
it.SetData(d);
args.ItemContainer = it;
args.IsContainerPrepared = true;
// This should probably go elsewhere, but for simplicity it's here :)
((ItemsWrapGrid)ItemsPanelRoot).ItemWidth = 100;
((ItemsWrapGrid)ItemsPanelRoot).ItemHeight = 100;
}
}
}
你能告诉你如何将'GridViewItems'添加到'GridView'吗?没有你的代码,就没有办法找出问题所在,以及为什么会发生。请参阅[mcve] – AVK
我已用最小的示例更新了该问题。 – Pragma