文本框中的UWP绑定在异步方法中不起作用
本文关键字:异步方法 绑定 不起作用 UWP 文本 | 更新日期: 2023-09-27 18:04:55
我有一个UWP应用程序。viewModel和Datacontext被正确设置,INotifiedPropertyChanged被正确实现,PropertyChanged被正确触发,绑定模式被设置为单向,但是只有当属性在viewModel的构造函数中被改变时,文本框才会更新。如果在async方法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>
这是我的viewModel:
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();
}
}
just change
PropertyChanged(this, new PropertyChangedEventArgs("propertyName"));
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
它正在工作,但唯一的通知UI得到的是属性名为"propertyName"已经改变,而不是你传递给OnPropertyChanged方法的名称