2017-04-14 27 views
0

我有一個GridviewItem。這個GridViewItem有一個ImageBrush的背景。現在我想在點擊某個按鈕時將此ImageBrush更改爲新的源代碼。如何更新UWP頁面上的圖像?

對於這個我使用:

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

最好的是,如果你有一個適當的屬性定義了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; } 
} 
相關問題