none
How to Bind SelectedItem Into the ListView.?

    Question

  • Hello Guys,

    I am working with ListView and I want to Bind SelectedItem Defualt but it will not working my XAML is like this

                    <ListView x:Name="MenuBarList" 
                        ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
                        Height="{Binding MainMenuHeight}"  
                        Width="{Binding MainMenuWidth}" 
                        ItemsSource="{Binding}" 
                        SelectedItem="{Binding Path=SelectedMainMenuOption, Mode=TwoWay}"
                        Foreground="White"
                        Background="#FF3D61D0"
                        SelectionMode="Single">
    


    so the SelectedMainMenuOption is the Property but it is not working is there any workaround so I can goahead thank you very much..

     


    Jitendra Jadav
    Monday, November 14, 2011 2:32 PM

All replies

  • u need to set the SelectedMainMenuOption property to the one of the possible values in the

    itemsource

    please put the code behind for better understanding of the issue..



    Thanks, BHavik
    Monday, November 14, 2011 2:36 PM
  • I dont want to add any of the code into the code behind we are following MVVM approach so the SelectedMainMenuOption is the my property of the ModelView and it is bind with the usercontrol.DataContext

    so still i din't get you answer what you are trying to explain me.

    can you more decribe it.

     even I had Assing the ItemsSource {Binding Path=Menu.Options} there will be atleast six item is there.

    Thank you.


    Jitendra Jadav
    • Edited by Jitendra Jadav Monday, November 14, 2011 3:02 PM Modify code
    Monday, November 14, 2011 2:41 PM
  • try out this example

    XAML

     <DockPanel>
            <ListView ItemsSource="{Binding ListOfEmp}" SelectedItem="{Binding SelectedEmployee}">
    
            </ListView>
    
        </DockPanel>


    ViewModel

     public class ViewModel : INotifyPropertyChanged
        {
    
    
            public ViewModel()
            {
                AddCommand = new DelegateCommand(OnAdd, AddCanExecute);
    
                listOfEmp.Add(new Employee() { Name = "One", SurName="aaa" });
                listOfEmp.Add(new Employee() { Name = "Two", SurName = "ccc" });
                listOfEmp.Add(new Employee() { Name = "Four", SurName = "ddd" });
                listOfEmp.Add(new Employee() { Name = "Abc", SurName = "bbb" });
    
                selectedEmployee = listOfEmp[2];
            }
    
            private Employee selectedEmployee;
    
            public Employee SelectedEmployee
            {
                get { return selectedEmployee; }
                set { selectedEmployee = value;
                OnPropertyChanged("SelectedEmployee");
                }
            }
    
            private ListCollectionView EmpCollectionView
            {
                get
                {
                    return (ListCollectionView)CollectionViewSource.GetDefaultView(ListOfEmp);
                }
            }
    
    
            private ObservableCollection<Employee> listOfEmp = new ObservableCollection<Employee>();
            public ObservableCollection<Employee> ListOfEmp
            {
                get { return listOfEmp; }
                set { listOfEmp = value; }
            }
    }


    Employee class

    public class Employee
        {
            public string Name { get; set; }
    
            public string SurName { get; set; }
        }


    so here i have made a property called selectedEmployee and assign it the value that i want...

    hope it helps u..


    Thanks, BHavik
    Monday, November 14, 2011 5:30 PM
  • This is same I had done but still it is not working I am wondering why it is not happning.

    I dont thik that I am missing in this code. but still my sample is not working still if you have any other workaround for it then pleas tell me I happy to take forward..

    Thank very much for your help.

     


    Jitendra Jadav
    Monday, November 14, 2011 5:54 PM
  • > my sample is not working still if you have any other workaround for it then pleas tell me I happy to take forward..

     

    try using following code. it forks fine.

    <Window x:Class="WpfApplication6.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
    
        <StackPanel>
            <WrapPanel>
                <Button Content="Prev" Click="Prev_Click" />
                <Button Content="Next" Click="Next_Click" />
            </WrapPanel>
            <ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"
                   DisplayMemberPath="Name">
            </ListView>
        </StackPanel>
    </Window>
    
    
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Linq;
    using System.Windows;
    
    namespace WpfApplication6
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                var data = LoadData();
                this.DataContext = new ViewModel { Items = data, SelectedItem = data[0] };
            }
    
            IList<object> LoadData()
            {
                return new ObservableCollection<object>(
                    Enumerable.Range(0, 10).Select(i => new { Name = "item" + i }));
            }
    
            private void Next_Click(object sender, RoutedEventArgs e)
            {
                var vm = (this.DataContext as ViewModel);
                var i = vm.Items.IndexOf(vm.SelectedItem);
                if (i + 1 < vm.Items.Count)
                    vm.SelectedItem = vm.Items[i + 1];
            }
            private void Prev_Click(object sender, RoutedEventArgs e)
            {
                var vm = (this.DataContext as ViewModel);
                var i = vm.Items.IndexOf(vm.SelectedItem);
                if (i - 1 >= 0)
                    vm.SelectedItem = vm.Items[i - 1];
            }
        }
    
        public class ViewModel : INotifyPropertyChanged
        {
            public IList<object> Items { get; set; }
    
            public object SelectedItem
            {
                get { return _SelectedItem; }
                set
                {
                    _SelectedItem = value;
                    OnPropertyChanged("SelectedItem");
                }
            }
            private object _SelectedItem;
    
            private void OnPropertyChanged(string p)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(p));
            }
            public event PropertyChangedEventHandler PropertyChanged = delegate { };
        }
    }
    
    

    Monday, November 14, 2011 8:07 PM
  • Hi Jitendra Jadav,

    I think you could double check if your ItemsSource property binding correctly, and then you could check if the selectedItem's path is correct.

     

    Best regards,


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, November 15, 2011 6:15 AM
    Moderator
  • Your sample is exactly right, even earlier I have RadCarousel so it was working perfectly right but in the ListView is not working I dont Know why but I had ckech out it is ItemsSource is binding perfectly what I Had did in this case I had added one Grid above the ListView and bind the Grid.DataContext = Menu.Options and say to the ListView ItemsSource={Binding} and it will give me the List of Item, but even I show the SelecetedItem I had binded with ListView.ItemTemplate and inside the DataTemplate there is StackPanel and I have two Item 1 Image and 2 Text so it will working perfeclty but when I am trying to show the Visual tree of the Listview that  time i dint find any SelectedItme into the ListView so is there any problem or else I am going to show my XAML so you could find more clue about this

    one more thing thank you for give me sample and put your effort than you once again

                <Grid Grid.Row="2" DataContext="{Binding Path=Menu.Options}">
                                   <Border x:Name="BDRounded" BorderThickness="0" CornerRadius="15" Background="White"/>
    
                    <ListView x:Name="MenuBarList" 
                                ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
                                Height="{Binding MainMenuHeight}"  
                                Width="{Binding MainMenuWidth}" 
                                ItemsSource="{Binding}" 
                                IsSynchronizedWithCurrentItem="True"
                                Foreground="White" Background="#FF3D61D0"
                                SelectionMode="Single" SelectedItem="{Binding Path=SelectedMainMenuOption, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    
                        <ListView.OpacityMask>
                            <VisualBrush Visual="{Binding ElementName=BDRounded}"/>
                        </ListView.OpacityMask>
    
    
                        
                        <ListView.Style>
                            <Style TargetType="{x:Type ListView}">
                                <Setter Property="BorderBrush" Value="White"/>
                                <Setter Property="BorderThickness" Value="0"/>
                                <Setter Property="Margin" Value="0"/>
                                <Setter Property="Width" Value="{Binding MainMenuWidth}"/>
                                <!-- here we go -->
                                <Style.Resources>
                                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Pink"/>
                                    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Pink"/>
                                </Style.Resources>
                            </Style>
                        </ListView.Style>
    
                        <ListView.ItemsPanel>
                            <ItemsPanelTemplate>
                                <WrapPanel Orientation="Vertical" />
                            </ItemsPanelTemplate>
                        </ListView.ItemsPanel>
    
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal" Focusable="False">
                                    <Image Source="{Binding IconPath}" 
                                           Focusable="False"
                                           HorizontalAlignment="Center"
                                           VerticalAlignment="Center"
                                           IsHitTestVisible="False"/>
    
                                    <TextBlock Text="{Binding Title}" 
                                               Focusable="False" 
                                               HorizontalAlignment="Center" 
                                               VerticalAlignment="Center" 
                                               FontFamily="Segoe UI"
                                               FontSize="26"
                                               IsHitTestVisible="False"/>
                                </StackPanel>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </Grid>
    

    try to figure out where I am wrong ...!!!

     


    Jitendra Jadav
    Tuesday, November 15, 2011 7:48 AM
  • > try to figure out where I am wrong

     
    could you please provide the related code behind in order to reproduce your issue?

     



    • Edited by Malobukv Tuesday, November 15, 2011 7:08 PM
    Tuesday, November 15, 2011 7:06 PM
  • Hi Jitendra jadav,

    As Malobukv said, you have to share more code with us, based on those xaml, it is hard to repro and provide you the solution.

     

    best regards,


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, November 17, 2011 5:17 AM
    Moderator
  • Hi Jitendra jadav,

    Any updates?


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, November 22, 2011 8:48 AM
    Moderator