如何在UWP中更新页面上的图像?

时间:2017-04-14 10:47:23

标签: c# uwp windows-10-universal

我有一个GridviewItem。这个GridviewItem有一个背景,它是一个ImageBrush。现在,我想在单击某个按钮时将此ImageBrush更改为新的源。

为此,我使用:

blck.Background = new ImageBrush(new BitmapImage(new Uri("ms-appx:///Assets/SensorBG.png")));

它确实有效,但只要我点击相应的GridviewItem,新图像就会显示。任何人都可以告诉我如何更新它而无需点击GridviewItem?

我已经尝试将其置于此区块内但没有成功:

            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                blck.Background = new ImageBrush(new BitmapImage(new Uri("ms-appx:///Assets/SensorBG.png")));
            }
            );

1 个答案:

答案 0 :(得分:1)

如果您已使用合适的属性定义 ItemClass 并使用适当的绑定实现 INotifyPropertyChanged ,那么最好的方法是,每次更改都会更新UI。这是一个小样本 - XAML:

<StackPanel>
    <Button Content="Change background of second item" Click="Button_Click"/>
    <GridView Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" ItemsSource="{x:Bind Items}">
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="local:ItemClass">
                <Border>
                    <Border.Background>
                        <ImageBrush ImageSource="{x:Bind Image, Mode=OneWay}"/>
                    </Border.Background>
                    <TextBlock Text="{x:Bind Name}"/>
                </Border>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</StackPanel>

和背后的代码:

public sealed partial class MainPage : Page
{
    public List<ItemClass> Items = new List<ItemClass>();

    public MainPage()
    {
        Items.Add(new ItemClass { Name = "First item", Image = new BitmapImage(new Uri("ms-appx:///Assets/StoreLogo.png")) });
        Items.Add(new ItemClass { Name = "Second item", Image = new BitmapImage(new Uri("ms-appx:///Assets/StoreLogo.png")) });
        this.InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e) => Items[1].Image = new BitmapImage(new Uri("ms-appx:///test.jpg"));
}

public class ItemClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void RaiseProperty(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

    private ImageSource image;
    public ImageSource Image
    {
        get { return image; }
        set { image = value; RaiseProperty(nameof(Image)); }
    }

    public string Name { get; set; }
}