我有一个模型对象,它的列表绑定到Gridview。这是我的模特课
public class ItemModel: BindableBase
{
public override bool Equals(object obj)
{
return this.Id == ((ItemModel)obj).Id;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
public static bool operator ==(ItemModel op1, ItemModel op2)
{
return op1.Id == op2.Id;
}
public static bool operator !=(ItemModel op1, ItemModel op2)
{
return op1.Id != op2.Id;
}
private Guid _id;
public Guid Id
{
set { SetProperty(ref this._id, value); }
get { return _id; }
}
private string _clue;
public string Clue
{
set { this.SetProperty(ref this._clue, value); }
get { return _clue; }
}
private string _boxId;
public string BoxId
{
set { this.SetProperty(ref this._boxId, value); }
get { return _boxId; }
}
public override string ToString()
{
return this.Clue;
}
有两种方法可以在我的页面中加载数据。第一个是整数,第二个是和ItemModel对象。对于第二种方式,必须选择网格传递给页面的相应项目。所以我的代码如下所示:
protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
// TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
if (navigationParameter is int)
{
BindByBoxId(navigationParameter);
}
else if (navigationParameter is ItemModel)
{
BindByWordObject(navigationParameter as ItemModel);
}
}
private async void BindByWordObject(ItemRepository passedItem)
{
ItemRepository repo = new ItemRepository();
var boxId = (int)passedItem.BoxId;
var item = await repo.GetWordsByBox(boxId);
this.DefaultViewModel["Items"] = item;
GroupNameTextBlock.Text = passedItem.Box.BoxName;
itemGridView.SelectedIndex = GetItemIndex(passedItem);
itemGridView.SelectionChanged += SelectChanged;
}
private int GetItemIndex(ItemModel item)
{
for(int i =0 ; i<itemGridView.Items.Count; i++)
{
if (((ItemModel)itemGridView.Items[i]) == item)
return i;
}
return -1;
}
private async void BindByBoxId(object navigationParameter)
{
ItemRepository repo = new ItemRepository();
var boxId = (int)navigationParameter;
var item = await repo.GetItemsByBox(boxId);
this.DefaultViewModel["Items"] = item;
GroupNameTextBlock.Text = item.First().Box.BoxName;
itemGridView.SelectedValue = -1;
itemListView.SelectedValue = -1;
itemGridView.SelectionChanged += SelectChanged;
}
我尝试SelectedValue
和SelectedItem
(在Windows应用商店应用中,它们可以用作seter和geter)但这些属性永远不会正常工作。我在gridview中选择相应项的解决方案是循环遍历gridview的项并找到项索引(GetItemIndex
方法)并使用SelectedIndex
属性。我想知道有什么替代方案和优化方式吗?因为在大量项目中循环会很糟糕!请告诉我。
答案 0 :(得分:0)
这是一年之后,但我今天只有类似的问题,并将分享我的发现:
尝试使用GridView事件DataContextChanged,其中参数args随ObservavleColletion一起提供,或者为null(如果此事件被触发两次,就像我的情况一样)
private void itemGridView_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
{
GridView oGridView = sender as GridView;
if (oGridView != null && args.NewValue != null)
{
ObservableCollection<yourclass> yourCol = args.NewValue as ObservableCollection<yourclass>;
for(int i= 0; i<yourCol.Count; i++)
// do your checking...
if (YourChecking) oGridView.SelectedIndex = i;
}
}