文本框中的UWP绑定工作在异步方法中不起作用

时间:2016-08-31 20:51:57

标签: c# mvvm data-binding uwp

我有一个UWP应用程序。正确设置了viewModel和Datacontext,正确实现了INotifiedPropertyChanged,正确触发了PropertyChanged,将绑定模式设置为OneWay,但只有在viewmodel的构造函数中更改了属性时才更新Textbox。如果在异步方法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();
    }

}

1 个答案:

答案 0 :(得分:1)

只需更改

PropertyChanged(this, new PropertyChangedEventArgs("propertyName"));

PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

它正在工作,但唯一的通知UI获取的是名为“propertyName”的属性已更改,您要传递给OnPropertyChanged方法的名称的内容