Can't change gridview itemssource

那年仲夏 提交于 2020-01-17 07:45:55

问题


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;


来源:https://stackoverflow.com/questions/16220843/cant-change-gridview-itemssource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!