问题
I have problem with DataContext in Windows Phone 8 project. When I run project and MainPage() is done - I see 1st GIF, but when I go Button_Click_1 - 1st GIF is still visible. I have no idea how DataContext work. Is there any way to set DataContext again and display 2nd GIF?
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
public Uri ImageSource { get; set; }
// Constructor
public MainPage()
{
InitializeComponent();
ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
ImageSource = new Uri("http://c.wrzuta.pl/wi7505/bcd026ca001736004fc76975/szczur-piwo-gif-gif", UriKind.Absolute);
this.DataContext = this;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
ImageSource = new Uri("http://0-media-cdn.foolz.us/ffuuka/board/wsg/image/1338/94/1338947099997.gif", UriKind.Absolute);
this.DataContext = this;
}
}
}
XAML
<imagetools:AnimatedImage x:Name="Image" Source="{Binding ImageSource, Converter={StaticResource ImageConverter}}" Margin="43,0,50,257" />
回答1:
You will want to implement INotifyPropertyChanged
so the Xaml
knows of the changes to the ImageSource
property.
Example:
public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
{
private Uri _imageSource;
public Uri ImageSource
{
get { return _imageSource; }
set { _imageSource = value; NotifyPropertyChanged("ImageSource"); }
}
// Constructor
public MainPage()
{
InitializeComponent();
ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
this.DataContext = this;
ImageSource = new Uri("http://c.wrzuta.pl/wi7505/bcd026ca001736004fc76975/szczur-piwo-gif-gif", UriKind.Absolute);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
ImageSource = new Uri("http://0-media-cdn.foolz.us/ffuuka/board/wsg/image/1338/94/1338947099997.gif", UriKind.Absolute);
}
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Notifies the property changed.
/// </summary>
/// <param name="property">The property.</param>
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
来源:https://stackoverflow.com/questions/14926779/imagetools-on-windows-phone-8-changing-imagesource-and-datacontext