我有一个模型对象,它的列表绑定到 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
属性。我想知道有什么替代和优化的方式适合我吗?因为循环大量的项目会很糟糕!!!请给我建议。