先生们,请帮助实施数据的主管更新。
应用操作:
- 该事件会定期下载一个 JSON 文件。
- 我们使用事件的签名方法来读取
Load();
这个文件并将所有数据输入到某个模型中。 - 我们进行数据绑定和输出。
目前我有这样一个“拐杖”(删除旧的数据绑定并用新的绑定它):
if (alertbox.ItemsSource != null) alertbox.ItemsSource = null;
alertbox.ItemsSource = News.Data.Posts;
你真的需要摆脱它。我尝试实施INotifyPropertyChanged
,但无论我做什么,数据仍然很旧......
实际上代码本身:
从 JSON 文件加载数据(主要方法Read
和静态方法方便Load
):
internal class Game
{
private static GameView Read(string fileName)
{
GameView data;
using (var file = File.OpenText(fileName))
{
var serializer = new JsonSerializer();
data = (GameView) serializer.Deserialize(file, typeof(GameView));
}
return data;
}
/// <summary>
/// Основные игровые данные.
/// </summary>
public static GameView Data;
/// <summary>
/// Загружаем JSON файл с игровыми данными.
/// </summary>
/// <param name="filename">Путь до JSON файла</param>
public static void Load(string filename = "temp")
{
if (filename == "temp") filename = $"{Settings.Program.Directories.Temp}/GameData.json";
Data = Read(filename);
}
}
型号GameView
:
public class GameView
{
public int Version { get; set; }
public string MobileVersion { get; set; }
public string BuildLabel { get; set; }
public int Time { get; set; }
public int Date { get; set; }
public List<Alert> Alerts { get; set; }
public List<double> ProjectPct { get; set; }
public string WorldSeed { get; set; }
}
public class Alert
{
[JsonProperty("_id")]
public Id Id { get; set; }
public Activation Activation { get; set; }
public Expiry Expiry { get; set; }
public MissionInfo MissionInfo { get; set; }
}
public class MissionInfo
{
public string MissionType { get; set; }
public string Faction { get; set; }
public string Location { get; set; }
public string LevelOverride { get; set; }
public string EnemySpec { get; set; }
public int MinEnemyLevel { get; set; }
public int MaxEnemyLevel { get; set; }
public double Difficulty { get; set; }
public int Seed { get; set; }
public int MaxWaveNum { get; set; }
public MissionReward MissionReward { get; set; }
public string ExtraEnemySpec { get; set; }
public List<string> CustomAdvancedSpawners { get; set; }
public bool? ArchwingRequired { get; set; }
public bool? IsSharkwingMission { get; set; }
}
我怎么打电话:
Game.Load();
alertbox.ItemsSource = Game.Data.Alerts;
嗯,目前最简单的ListBox
:
<ListBox x:Name="alertbox" Background="{x:Null}" BorderBrush="{x:Null}">
<ListBox.ItemTemplate>
<DataTemplate >
<Label Content="{Binding MissionInfo.Location}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在这种情况下帮助实现对在加载 JSON 文件后立即更新界面中的数据的支持。整个项目上传到GitHub
对于初学者,您将无法绑定到字段。绑定必须是属性。
Game
然后,绑定到静态属性是不方便的,游戏本身就是一个实体,所以让类的方法和属性成为非静态的对你来说是有意义的。此外,您必须实施INotifyPropertyChanged
,不要在您的代码中看到它。VM
我们从这里获取基类,我们写:此外,您的内部类是不可变的吗?如果没有,他们需要实施
INotifyPropertyChanged
. 并且列表需要实现INotifyCollectionChanged
,也就是说,理论上你只需要ObservableCollection<T>
:对于您计划绑定的其他类也是如此。
这样,您就可以在 XAML 中组织绑定。