简体   繁体   中英

How to update an image on a page in UWP?

I've got a GridviewItem. This GridviewItem has a background which is an ImageBrush. Now I want to change this ImageBrush to a new source when clicking a certain button.

For this I'm using:

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

It does work however the new image only shows whenever I click on the corresponding GridviewItem. Can anyone tell me how to update it without having to click on the GridviewItem?

I've already tried to put it within this block with no success:

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

The best would be, if you have defined your ItemClass with suitable properties and implement INotifyPropertyChanged - with appropriate binding, every change will update the UI. Here is a small sample - 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>

and the code behind:

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; }
}

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