无法更改GridView项目源 [英] Can't change gridview itemssource
问题描述
我正在尝试在gridview(具有ItemTemplates,其中有100个绿色框)中更改框的颜色.
I'm trying to change a box's color in a gridview(that has ItemTemplates which has 100 green boxes).
首先,我创建了一个列表(作为我的班级键入),并将所有项目添加到列表中,并将列表添加到了gridview源中:
First, I created a list(which typed as my class) and I added all items to list and I added list to my gridview source :
grid1.ItemsSource = boxlist;
之后,我为gridview上的项目单击添加了一个click事件.我希望当我单击某个项目时,该项目的颜色将被更改.因此,我按如下方式编辑了列表:
After, I added a click event for item click on gridview. I want that when I clicked to an item, this item's color will be changed. So I edited list as it :
int id = ((Boxes)e.ClickedItem).id;
boxlist[id].color = "DarkRed";
grid1.ItemsSource = boxlist;
我尝试过更改点击项的颜色,但是它不起作用.列表项的颜色正在成功更改,但是gridview无法使用它.但是我希望gridview可以使用这个新资源.我该如何解决这个问题?
I tried it to change color of clicked item but it doesn't work. Color of list item is changing succesfully but gridview is not taking it. But I want that gridview takes this new source. How can I solve this problem?
我的课:
class Boxes
{
public int id { get; set; }
public string color { get; set; }
}
GridView的XAML
XAML of GridView
<GridView x:Name="grid1" HorizontalAlignment="Left" Margin="354,41,0,0" VerticalAlignment="Top" Width="800" Height="650" SelectionMode="None" IsItemClickEnabled="True" ItemClick="grid1_ItemClick">
<GridView.Resources>
<DataTemplate x:Key="DataTemplate1">
<Grid Height="50" Width="50">
<Rectangle x:Name="rect1" Width="50" Height="50" Fill="{Binding color}" Tag="{Binding id}"/>
</Grid>
</DataTemplate>
</GridView.Resources>
<GridView.ItemTemplate>
<StaticResource ResourceKey="DataTemplate1"/>
</GridView.ItemTemplate>
</GridView>
推荐答案
在设置新值之前,您必须使ItemSource为空:
You have to null the ItemSource just before you set the new value:
ctlList.ItemsSource = null;
ctlList.ItemsSource = YourObjects;
我建议使用DataContext和Binding代替您的解决方案:
I recommand to use DataContext and Binding instead of your solution:
http://www.codeproject.com/Articles/30905/WPF-DataGrid-Practical-Examples
这篇关于无法更改GridView项目源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!