在Windows Phone中更新绑定/静态资源

时间:2015-03-19 17:07:17

标签: c# xaml binding windows-runtime

在我的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中不会更改。我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您需要使用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));
    }
}