Can't change gridview itemssource

2019-08-23 02:26发布

问题:

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>

回答1:

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



回答2:

You need to use DataContext instead like this:

grid1.DataContext = boxlist;