0

C# - WPF I have a listbox ("lstCustomer") popolated with a List of "Id_Name" objects

From a point of the code i obtain an ID - for example "2" How can I select programmatically the element of the listBox with 2 as ID ?

lstCustomer.SelectedIndex = ????

CODE - POPOLATE THE LIST

List<Id_Name> list = new ();
list.Add(new Id_Name { Id = "1" , Name = "John" });
list.Add(new Id_Name { Id = "2", Name = "Jim" });
list.Add(new Id_Name { Id = "3", Name = "Frank" });
lstCustomer.ItemsSource = list;

XAML - LISTBOX and DATATEMPLATE

<ListBox x:Name="lstCustomer"  ItemTemplate="{StaticResource ResourceKey=Id_Name_Template}" />


<DataTemplate  x:Key="Id_Name_Template">
                <StackPanel>
                    <Grid >
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0">
                            <Run FontWeight="Bold" Text="{Binding Id}"/>
                        </TextBlock>
                        <TextBlock Grid.Column="1" FontStyle="Italic" Text="{Binding Name}" />
                    </Grid>
                </StackPanel>
            </DataTemplate>
Vez
  • 55
  • 8

1 Answers1

1

If you are not hell bent on using the index i'd suggest binding the SelectedItem property of the ListBox:

<ListBox x:Name="lstCustomer"
         ItemTemplate="{StaticResource ResourceKey=Id_Name_Template}"
         SelectedItem="{Binding SelectedId_Name}"/>

and then in your ViewModel you can just set that property:

public Id_Name SelectedId_Name { get; set; }   //Needs to call your implementation of INotifyPropertyChanged   

[...]  
SelectedId_Name = list.Where( x => x.Id == "2").FirstOrDefault();

Or make use of the ListBox's built-in SelectedValue feature:

<ListBox x:Name="lstCustomer"
         ItemTemplate="{StaticResource ResourceKey=Id_Name_Template}"
         SelectedValuePath="Id"
         SelectedValue="{Binding SelectedId}"/>

with

public string SelectedId { get; set; } // plus notification

[...]
SelectedId = "2";
Clemens
  • 123,504
  • 12
  • 155
  • 268
T.Schwarz
  • 130
  • 6