【发布时间】:2018-10-10 00:04:35
【问题描述】:
通过 NavigationView 控件更改页面会导致某些数据绑定失败/丢失。
数据模型:
public class Flashpoint
{
private string name;
private string description;
private string image;
public string Name
{
get { return name; }
set { name = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}
public string Image
{
get { return image; }
set { image = value; }
}
}
页面 xaml:
<Page
x:Class="Braytech_3.Views.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="using:Braytech_3.Views"
xmlns:data="using:Braytech_3.Models"
Style="{StaticResource PageStyle}"
mc:Ignorable="d">
<Grid x:Name="ContentArea">
<StackPanel Height="400" HorizontalAlignment="Left" VerticalAlignment="Top">
<Image HorizontalAlignment="Center" VerticalAlignment="Center" Source="{x:Bind CurrentFlashpoint.Image, Mode=OneWay}" Stretch="UniformToFill"/>
<TextBlock Text="{x:Bind CurrentFlashpoint.Name, Mode=OneWay}" />
</StackPanel>
页面cs:
namespace Braytech_3.Views
{
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
Flashpoint CurrentFlashpoint { get; set; }
public MainPage()
{
InitializeComponent();
Render();
}
public event PropertyChangedEventHandler PropertyChanged;
private void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (Equals(storage, value))
{
return;
}
storage = value;
OnPropertyChanged(propertyName);
}
private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private async void Render()
{
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
StorageFile APIData = await tempFolder.GetFileAsync("APIData.json");
string json = await FileIO.ReadTextAsync(APIData);
Universal request = JsonConvert.DeserializeObject<Universal>(json);
foreach (var challenge in request.response.data.challenges)
{
if (challenge.type == "flashpoint")
{
CurrentFlashpoint = new Models.Flashpoint
{
Name = challenge.name,
Description = challenge.description,
Image = $"/Assets/Images/{ challenge.slug }.jpg"
};
}
}
}
}
}
从上面的代码摘录中省略了一个绑定到图像控件下方的枢轴控件的 ObservableCollection。它按预期工作。供应商页面也使用 ObservableCollection。因为我只是想绑定单个项目(文本块、图像),所以我不确定如何使用 ObservableCollection,如果我什至应该尝试对我来说它相当于我正在尝试的项目数组绑定单个项目。
使用实时树检查器,我能够在数据绑定丢失之前和之后检查图像控件,但这并没有让我找到原因的答案。
为什么它会失去绑定,我该如何修复它?
【问题讨论】:
-
您是否尝试过为 MainPage 设置
NavigationCacheMode="Required"? -
@NicoZhu-MSFT 那真是太棒了!容易修复。但是为什么会出现这个问题,有没有更好的方法来解决我的问题,在代码中,以避免依赖这个页面属性?
-
我无法理解这句谚语的意思。请告诉我它是否有效。
-
这很奇怪,你能介意分享一个迷你样本。我想检查一下细节。
-
@NicoZhu-MSFT 是的,它有效。 github.com/justrealmilk/Braytech-3
标签: c# xaml uwp windows-template-studio