强制刷新ListView

时间:2018-08-27 10:21:19

标签: c# wpf listview

我正在使用C#,我有一个使用ListView的项目。

我将尝试总结一下我的情况:

有我的ListView(我删除了一些部分):

<ListView x:Name="listItem">
    <ListView.View >
        <GridView>
            <GridViewColumn Header="Image" Width="268" x:Name="scoreGridItem" >
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Grid>
                            <StackPanel Orientation="Horizontal">
                                <Rectangle x:Name="scoreIndicator">
                                    <Rectangle.Width>
                                        <MultiBinding Converter="{StaticResource scoreConv}">
                                            <Binding Path="Score" />
                                            <Binding Path="Min" />
                                            <Binding Path="Max" />
                                        </MultiBinding>
                                    </Rectangle.Width>
                                </Rectangle>

                                <Grid x:Name="grid" Height="40" Width="40" >
                                    <Border BorderThickness="2" BorderBrush="{Binding BorderColor2}">
                                        <Image Width="38" Height="38" Source="{Binding Picture}"/>
                                    </Border>
                                </Grid>
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

该列表在source中有一个自定义类:

public class ControlItem
{
    public int Score { get; set; }
    public int Min { get; set; }
    public int Max { get; set; }
    public int Index { get; set; }

    public BitmapSource Picture { get; set; }
}

在视图中添加新项目时,将加载默认的Picture。线程启动,结束时,我更改Index的值。然后,我想更改Picture,但列表视图中的图像不变。

如何强制刷新?

1 个答案:

答案 0 :(得分:2)

ControlItem 应该实现接口 INotifyPropertyChanged 。 并且您的媒体资源必须调用 OnPropertyChanged 事件。

public class ControlItem : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler propertyChanged;
    private BitmapSource picture;

    public int Score { get; set; }
    public int Min { get; set; }
    public int Max { get; set; }
    public int Index { get; set; }

    public BitmapSource Picture
    {
       get { return picture; }
       set 
           {
               picture = value;
               NotifyPropertyChanged();
            }
    }

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
       if (PropertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}