简体   繁体   中英

When calling the method from MainPage.xaml.cs it runs but the UI doesn't update

I'm creating an UWP app that is supposed to get some data from an API and display it, that happens on the "Refresh()" method.

Everything works fine until I try to do a search, that is the "Search()" method.

The "Search()" method is called from the MainPage.

public sealed partial class MarvelMenu : Page, INotifyPropertyChanged
{
    //Backing field.
    private ObservableCollection<Character> _marvelCharacters = new ObservableCollection<Character>();

    //Property
    public ObservableCollection<Character> MarvelCharacters
    {
        get { return _marvelCharacters; }

        set
        {
            if (value != _marvelCharacters)
            {
                _marvelCharacters = value;

                //Notify of the change.
                NotifyPropertyChanged();
            }
        }
    }

    //PropertyChanged event.
    public event PropertyChangedEventHandler PropertyChanged;

    //PropertyChanged event triggering method.
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private ObservableCollection<ComicBook> MarvelComics;

    public MarvelMenu()
    {
        this.InitializeComponent();
        MarvelComics = new ObservableCollection<ComicBook>();
    }

    private async void Page_Loaded(object sender, RoutedEventArgs e)
    {
        var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///VoiceCommandDictionary.xml"));
        await VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(storageFile);
        Refresh();
    }

    public async void Refresh()
    {
        MyProgressRing.Visibility = Visibility.Visible;
        MyProgressRing.IsActive = true;
        ErrorTextBlock.Text = "";
        MarvelCharacters.Clear();

        while (MarvelCharacters.Count < 20)
        {
            Task t = MarvelFacade.PopulateMarvelCharactersAsync(MarvelCharacters);
            await t;
        }

        try
        {
            this.MasterListBox.SelectedIndex = 0;
        }

        catch (Exception)
        {
            return;
        }

        MyProgressRing.IsActive = false;
        MyProgressRing.Visibility = Visibility.Collapsed;
        ErrorTextBlock.Text = MarvelFacade.errorMessage;
        var attribute = await MarvelFacade.GetCharacterDataWrapperAsync();
        var myAttribute = attribute.attributionText;

        try
        {
            AttributeTextBlock.Text = myAttribute;
        }

        catch (Exception)
        {
            return;
        }
    }

    public async void Search(string searchedCharacter)
    {
        MyProgressRing.Visibility = Visibility.Visible;
        MyProgressRing.IsActive = true;
        ErrorTextBlock.Text = "";
        MarvelCharacters.Clear();
        Task t = MarvelFacade.PopulateMarvelCharactersByNameAsync(searchedCharacter, MarvelCharacters);
        await t;
        MyProgressRing.IsActive = false;
        MyProgressRing.Visibility = Visibility.Collapsed;
        ErrorTextBlock.Text = MarvelFacade.errorMessage;
    }

While running the app in debug mode I found that the C# code runs perfectly and actually retrieves the searched data from the API, however it is not displayed. Even though I see Visual Studio go through each step in that method none of it is actually displayed.

        <ListBox Name="MasterListBox"
                 ScrollViewer.VerticalScrollBarVisibility="Hidden"
                 ItemsSource="{x:Bind MarvelCharacters}"
                 Grid.RowSpan="3"
                 IsHitTestVisible="True"
                 SelectionChanged="MasterListBox_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate x:DataType="data:Character">
                    <ListBoxItem Style="{StaticResource ListBoxItemStyle}"
                                 Margin="-12,-11,-12,-13"
                                 IsHitTestVisible="False">
                        <StackPanel Orientation="Horizontal">
                            <Ellipse Width="40"
                                     Height="40"
                                     Margin="4">
                                <Ellipse.Fill>
                                    <ImageBrush ImageSource="{x:Bind thumbnail.small}"/>
                                </Ellipse.Fill>
                            </Ellipse>
                            <TextBlock Text="{x:Bind name}"
                                       VerticalAlignment="Center"
                                       Width="180"
                                       TextTrimming="WordEllipsis"
                                       FontSize="15"
                                       Margin="10,0,0,0"/>
                        </StackPanel>
                    </ListBoxItem>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

My ListBox is binding to "MarvelCharacters" that is an public ObservableCollection properties. So it displays fine when the app is launched but it does not refresh to show the search results.

Any one can help me I would really appreciate it.

The binding in Xaml has a property known as 'Mode'. This property defines the way it is binded.

There a 3 Modes : OneTime,OneWay,TwoWay

OneTime : using will let u bind ur data to ur UI only once and that is during intialization. after that the UI is on its own. x:Bind has default mode setup to OneTime While classic binding ( {Binding} ) has default to setup to OneWay

OneWay : Using this will ensure Your UI Updates every time the Data Updates.

{x:Bind name,Mode=OneWay}

{Binding name,Mode=OneWay}

while Classic binding doesn't require the explicit declaration you can simply bind but for Compiled Binding Explicit declaration is Necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM