【发布时间】:2017-01-08 14:03:47
【问题描述】:
我有一个 UWP 应用程序。 viewModel 和 Datacontext 设置正确,INotifiedPropertyChanged 正确实现,PropertyChanged 正确触发,Binding Mode 设置为 OneWay 但只有在 viewmodel 的构造函数中更改属性时才会更新文本框。如果在异步方法 loadJSONFromResources 中改变了它就不起作用了。
这是我的 XAML:
<Page
x:Class="VokabelFileErstellen.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VokabelFileErstellen"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<local:ViewModel x:Name="viewModel"/>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" DataContext="{StaticResource ResourceKey=viewModel}">
<TextBlock Style="{StaticResource HeaderTextBlockStyle}" Margin="20,0,0,0" >
<Run Text="Anzahl Vokabeln: "/>
<Run Text="{Binding Count, Mode=OneWay}"/>
</TextBlock>
</Grid>
</Page>
这是我的视图模型:
class ViewModel : INotifyPropertyChanged
{
private int count;
public List<Vokabel> Buecher { get; set; }
public int Count
{
get { return count; }
set
{
if (value != count)
{
count = value;
OnPropertyChanged("Count");
}
}
}
public ViewModel()
{
Count = 1;
}
public async void jsonLaden()
{
FileOpenPicker picker = new FileOpenPicker
{
SuggestedStartLocation = PickerLocationId.ComputerFolder
};
picker.FileTypeFilter.Add(".json");
IStorageFile file = await picker.PickSingleFileAsync();
loadJSONFromResources(file);
}
public async void loadJSONFromResources(IStorageFile file)
{
string json = await FileIO.ReadTextAsync(file);
Buecher = JsonConvert.DeserializeObject<List<Vokabel>>(json);
Count = Buecher.Count;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("propertyName"));
}
}
这是我的 MainPage 代码:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
viewModel.jsonLaden();
}
}
【问题讨论】:
标签: c# mvvm data-binding uwp