0

I'm trying to change a box's color in a gridview(that has ItemTemplates which has 100 green boxes).

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;

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;

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?

My class :

class Boxes
{
    public int id { get; set; }
    public string color { get; set; }
}

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>
Ali Avcı
  • 1,281
  • 1
  • 11
  • 24

2 Answers2

2

You have to null the ItemSource just before you set the new value:

ctlList.ItemsSource = null;
ctlList.ItemsSource = YourObjects;

I recommand to use DataContext and Binding instead of your solution:

http://www.codeproject.com/Articles/30905/WPF-DataGrid-Practical-Examples

Kai
  • 1,953
  • 2
  • 13
  • 18
  • Actually I saw your post before times but when I set null and re-set to list again, It takes some while so it is not fast. grid1.Items does not contains any method like "Refresh". – Ali Avcı Apr 25 '13 at 18:46
  • 1
    That is the only solution in your case. What do you mean when you say "it is not fast"? How large is your list? – Kai Apr 25 '13 at 18:50
  • No. I mean that when you clear a list and refill all items, it takes a while. You can try in visual studio. Try your answer and see. – Ali Avcı Apr 25 '13 at 21:06
0

You need to use DataContext instead like this:

grid1.DataContext = boxlist;
albattran
  • 1,887
  • 1
  • 12
  • 16