1

我在 Windows Phone 8 项目中遇到 DataContext 问题。当我运行项目并且 MainPage() 完成时 - 我看到了第一个 GIF,但是当我去 Button_Click_1 时 - 第一个 GIF 仍然可见。我不知道 DataContext 是如何工作的。有没有办法再次设置 DataContext 并显示第二个 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" />
4

1 回答 1

3

您将需要实施INotifyPropertyChanged以便Xaml了解对ImageSource属性的更改。

例子:

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));
        }
    }
}
于 2013-02-17T23:01:22.240 回答