简体   繁体   中英

Can't change gridview itemssource

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>

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

您需要使用DataContext,如下所示:

grid1.DataContext = boxlist;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM