none
ListView does not select SelectedItem when it is set by code RRS feed

  • Question

  • Hello,
    below is the code. I have tried CleanSolution. I have deleted the files in the bin and obj folder.
    When i select an ListView item with the mouse Obj_Entry_Nutrition_2 is set correctly. When i set Obj_Entry_Nutrition_2 in code
    the ListView does not react.
    What can i do?

    <Page
        x:Class="P19.Entry_Meal_Item.BLS_Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:app="using:P19"  
        xmlns:local="using:P19.Entry_Meal_Item"
        xmlns:Entry_Nutrition_2="using:P19.Entry_Nutrition_2"  
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    
      <Page.Resources>
        <CollectionViewSource x:Name="Entry_Nutrition_2_Collection" 
             Source="{x:Bind Entry_Nutrition_2:Entry_Nutrition_2_ViewModel.SingleInstance.Entry_List.Values}">
        </CollectionViewSource>
      </Page.Resources>
    
      <ScrollViewer MinHeight="200" MinWidth="200" 
                    HorizontalScrollBarVisibility="Auto" 
                    VerticalScrollBarVisibility="Auto"
                    IsVerticalRailEnabled="True"
                    IsEnabled="True">
    
        <RelativePanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    
          <TextBox x:Name="Entry_Nutrition_2_Search_Text" Header="Suche" 
                   HorizontalAlignment="Stretch"
                   Margin="8, 10" FontSize="14" MinWidth="300" 
                   TextChanged="Entry_Nutrition_2_Search_Text_TextChanged"/>
    
          <ListView x:Name="Entry_Nutrition_2_List_ListView"
                    ItemsSource="{Binding Source={StaticResource Entry_Nutrition_2_Collection}}"    
                    SelectionChanged="Entry_Nutrition_2_List_ListView_Selection_Changed"
                    SelectionMode="Single" Margin="8"  MaxHeight="400"
                    SelectedItem="{x:Bind Obj_Entry_Nutrition_2, Mode=TwoWay}"
                    RelativePanel.AlignLeftWith="Entry_Nutrition_2_Search_Text"
                    RelativePanel.Below="Entry_Nutrition_2_Search_Text">
    
            <ListView.ItemTemplate>
              <DataTemplate x:DataType="Entry_Nutrition_2:Entry_Nutrition_2">
                <StackPanel Orientation="Horizontal">
    
                  <TextBlock Text="{x:Bind Title, Mode=TwoWay}" FontSize="12" MinWidth="100"/>
    
                  <TextBlock Text="{x:Bind BLS_Schluessel, Mode=TwoWay}" FontSize="12" MinWidth="100" 
                             Margin="15"/>
    
                </StackPanel>
              </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    
          <TextBox x:Name="Entry_Nutrition_2_Title_TextBox" Header="Nahrungsmittel" 
                   HorizontalAlignment="Stretch"
                   RelativePanel.RightOf="Entry_Nutrition_2_List_ListView"
                   RelativePanel.AlignTopWith="Entry_Nutrition_2_List_ListView"
                   Margin="25" FontSize="14" IsReadOnly="True"/>
        </RelativePanel>
    
      </ScrollViewer>
    
      <Page.BottomAppBar>
        <CommandBar>
          <AppBarButton Icon="Back" Label="Zurück" IsEnabled="True" Click="Back_Button_Click"/>
        </CommandBar>
      </Page.BottomAppBar>
    </Page>
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    
    // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
    
    namespace P19.Entry_Meal_Item
    {
      /// <summary>
      /// An empty page that can be used on its own or navigated to within a Frame.
      /// </summary>
      public sealed partial class BLS_Page : Page
      {
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        // Internal / Public Konstanten.
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    
        // NCN = Namespace_Class_Name.
        public static readonly string NCN = string.Concat
                                            (typeof(BLS_Page).Namespace, ".",
                                             nameof(BLS_Page));
    
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        // Protected / Private Variablen.
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    
        // ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        // Public / Internal Property Prozeduren. 
        // ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        
        public Entry_Nutrition_2.Entry_Nutrition_2 Obj_Entry_Nutrition_2 { get; set; }
    
    
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        // Obj bezogene Schlüsselereignisse und Schlüsselprozeduren.
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    
        public BLS_Page()
        {
          this.InitializeComponent();
    
          Entry_Nutrition_2_List_ListView.ItemsSource =
          (from e in
                Entry_Nutrition_2.Entry_Nutrition_2_ViewModel.SingleInstance.Entry_List.Values
           orderby e.Title
           select e);
        }
    
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
          Entry_Nutrition_2_Search_Text.Focus(FocusState.Programmatic);
        }
    
        private void Entry_Meal_Item_Page_Loaded(object sender, RoutedEventArgs e)
        {
        }
    
    
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        // Control Events.
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    
        // pn = Namespace_Class_Name + Procedure_Name. 
        internal static readonly string Back_Button_Click_pn
            = string.Concat(NCN, ".", nameof(Back_Button_Click));
    
        private async void Back_Button_Click(object sender, RoutedEventArgs e)
        {
          if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack();
        }
    
    
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        // Protected override Prozeduren.    
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    
        private void Entry_Nutrition_2_Search_Text_TextChanged(object sender, TextChangedEventArgs e)
        {
          TextBox t = (TextBox)sender;
          string s = t.Text;
    
          Entry_Nutrition_2.Entry_Nutrition_2 entry_nutrition_2 = null;
    
          if (string.IsNullOrEmpty(s))
          { entry_nutrition_2 = null; }
          else
          {
            //foreach (Entry_Nutrition.Entry_Nutrition n in
            //       Entry_Nutrition.Entry_Nutrition_ViewModel.SingleInstance.Entry_Nutrition_List.Values)
            //{
            //  if (n.Entry_Nutrition_Title.ToLower().StartsWith(s.ToLower()))
            //  {
            //    entry_nutrition = n;
            //    break;
            //  }
            //}
    
            System.Linq.IOrderedEnumerable<Entry.Entry> k =
            (System.Linq.IOrderedEnumerable<Entry.Entry>)
            Entry_Nutrition_2_List_ListView.ItemsSource;
    
            foreach (Entry_Nutrition_2.Entry_Nutrition_2 n in k)
            {
              if (n.Entry_Nutrition_Title.ToLower().StartsWith(s.ToLower()))
              {
                entry_nutrition_2 = n;
                break;
              }
            }
    
          }
          Obj_Entry_Nutrition_2 = entry_nutrition_2;
        }
    
        private void Entry_Nutrition_2_List_ListView_Selection_Changed(object sender, SelectionChangedEventArgs e)
        {
          if (e.AddedItems.Count > 0)
          {
            Entry_Nutrition_2.Entry_Nutrition_2 newselection;
    
            newselection = (Entry_Nutrition_2.Entry_Nutrition_2)e.AddedItems[0];
            Entry_Nutrition_2_List_ListView.ScrollIntoView(newselection, ScrollIntoViewAlignment.Leading);
          }
    
        }
      }
    }
    


    Saturday, July 13, 2019 10:14 AM

Answers

  • Hi  Markus,

    Through the analysis of your question, I think your main problem is that the code modifies the data, but the UI does not make the corresponding change.

    Here is the way to fix it:

    1. Add INotifyPropertyChanged interface on Page:

    public sealed partial class BLS_Page : Page,INotifyPropertyChanged
    {
     ...
     public BLS_Page()
     {
       this.InitializeComponent();
       ...
     }
     
     ...
     
     public event PropertyChangedEventHandler PropertyChanged;
     public void OnPropertyChanged(string propertyName = "")
     {
       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
     }
    }

    2. Raise Property Changed notification when you change the data:

    private void Entry_Nutrition_2_Search_Text_TextChanged(object sender, TextChangedEventArgs e)
    {
      ...
      Obj_Entry_Nutrition_2 = entry_nutrition_2;
      OnPropertyChanged("Obj_Entry_Nutrition_2");
    }

    Data and UI do not interfere with each other. If you change the data and want the UI to change, you need to notify it.

    That’s why your TextBox can’t respond to data changes.

    Just like the two countries, not only need the road, but also the messenger.

    Binding way is the road, while INotifyPropertyChanged is the messenger.

    Best Regards.


    • Marked as answer by Markus222 Monday, July 15, 2019 11:08 AM
    Monday, July 15, 2019 5:47 AM

All replies

  • In XAML
         <ListView x:Name="Entry_Nutrition_2_List_ListView"
                    ItemsSource="{Binding Source={StaticResource Entry_Nutrition_2_Collection}}"    
                    SelectionChanged="Entry_Nutrition_2_List_ListView_Selection_Changed"
                    SelectionMode="Single" Margin="8"  MaxHeight="400"
                    SelectedItem="{x:Bind Obj_Entry_Nutrition_2, Mode=TwoWay}"
                    RelativePanel.AlignLeftWith="Entry_Nutrition_2_Search_Text"
                    RelativePanel.Below="Entry_Nutrition_2_Search_Text">
    
    when i set Obj_Entry_Nutrition_2 in code i would expect that the item is selected in the listview.
    But i this time i must explicitly do the following
          Obj_Entry_Nutrition_2 = entry_nutrition_2;
          Entry_Nutrition_2_List_ListView.SelectedItem = Obj_Entry_Nutrition_2;
    
    Many times before it was enough to set the variable which was assigned to SelectedItem in XAML. But this time i must set .SelectedItem in Code explicitly. Why?


    Saturday, July 13, 2019 10:47 AM
  • And the binding does not function. When the .SelectedItem Variable is updated by selection the TextBox is not updated. I must set the TextBox Text in code. The Obj_Entry_Nutrition_2 variable does point to the right object. But the Property is not shown in the TextBox.

    Why is this. Things that do many times run sometimes don't in Visual Studio? This costs much time!



          <TextBox Text="{x:Bind Obj_Entry_Nutrition_2.Title, Mode=TwoWay}"
                   x:Name="Entry_Nutrition_2_Title_TextBox" Header="ausgewähltes Nahrungsmittel" 
                   HorizontalAlignment="Stretch"
                   RelativePanel.RightOf="Entry_Nutrition_2_List_ListView"
                   RelativePanel.AlignTopWith="Entry_Nutrition_2_List_ListView"
                   Margin="25" FontSize="14"/>



    • Edited by Markus222 Saturday, July 13, 2019 11:14 AM
    Saturday, July 13, 2019 11:12 AM
  • This issues are allways with XAML!
    Saturday, July 13, 2019 11:32 AM
  • Hi  Markus,

    Through the analysis of your question, I think your main problem is that the code modifies the data, but the UI does not make the corresponding change.

    Here is the way to fix it:

    1. Add INotifyPropertyChanged interface on Page:

    public sealed partial class BLS_Page : Page,INotifyPropertyChanged
    {
     ...
     public BLS_Page()
     {
       this.InitializeComponent();
       ...
     }
     
     ...
     
     public event PropertyChangedEventHandler PropertyChanged;
     public void OnPropertyChanged(string propertyName = "")
     {
       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
     }
    }

    2. Raise Property Changed notification when you change the data:

    private void Entry_Nutrition_2_Search_Text_TextChanged(object sender, TextChangedEventArgs e)
    {
      ...
      Obj_Entry_Nutrition_2 = entry_nutrition_2;
      OnPropertyChanged("Obj_Entry_Nutrition_2");
    }

    Data and UI do not interfere with each other. If you change the data and want the UI to change, you need to notify it.

    That’s why your TextBox can’t respond to data changes.

    Just like the two countries, not only need the road, but also the messenger.

    Binding way is the road, while INotifyPropertyChanged is the messenger.

    Best Regards.


    • Marked as answer by Markus222 Monday, July 15, 2019 11:08 AM
    Monday, July 15, 2019 5:47 AM
  • Hello,

    thank you. I forgot to use INotifyPropertyChanged.

    Monday, July 15, 2019 11:08 AM