【问题标题】:Update binding/staticresource in Windows Phone更新 Windows Phone 中的绑定/静态资源
【发布时间】:2015-03-19 17:07:16
【问题描述】:

在我的 xaml 代码中,我将我的类“Feed”添加到我的资源中。像这样:

<Page.Resources>
    <data:Feed x:Key="Feed"></data:Feed>
</Page.Resources>

该类包含属性 Apod 和稍后更新该属性的方法。

private ApodModel _apod;
public ApodModel Apod
{
    get { return _apod; }
    set { _apod = value; }
}
public Feed()
{
    DownloadApod();
}
private async void DownloadApod()
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(new Uri("http://spacehub.azurewebsites.net/api/apod", UriKind.Absolute));
            if (response.IsSuccessStatusCode)
            {
                string json = await response.Content.ReadAsStringAsync();
                Apod = JsonConvert.DeserializeObject<ApodModel>(json);
                var apod = new AppSettings<ApodModel>();
                await apod.SaveAsync("Apod", Apod);
            }
        }
    }
    catch (Exception)
    {
    }
}

在我的 XAML 中,我与属性的绑定如下所示:

<StackPanel DataContext="{StaticResource Feed}">
    <TextBlock Text="{Binding Apod.Description}">
</StackPanel>

当我调试属性 Apod 时,它会更新,但在 XAML 中没有改变。我做错了什么?

【问题讨论】:

    标签: c# xaml binding windows-runtime


    【解决方案1】:

    您需要在“Apod”属性更改时通知视图(否则,它将最初读取属性值作为其默认值null,并且永远不会再次读取)。为此,请让您的“Feed”类实现 INotifyPropertyChanged,并在“Apod”属性设置器中引发 PropertyChanged 事件。

    【讨论】:

      【解决方案2】:

      你需要使用 INotifyPropertyChange 来实现你的类

      它们实现接口。

      private ApodModel _apod;
      public ApodModel Apod
      {
          get { return _apod; }
          set { _apod = value; 
                NotifyPropertyChange("Apod");
              }
      }
      
      public event PropertyChangedEventHandler PropertyChanged;
      protected void NotifyPropertyChange(string name)
      {
          if(PropertyChanged!=null)
          {
              PropertyChanged(this,new PropertyChangedEventArgs(name));
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-15
        • 2011-09-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多