Listbox bound to ObservableCollection, Set SelectedIndex to last one
-
Hi! I have an observablecollection which is instanced in xaml. A listbox is bound to this collection. Binding works great, no problems so far. What I'm struggling with is how to force the listbox via xaml to select the last index available when the observablecollection fires an event. e.g: ((int)2 =) oscoll.Count(); SelectedIndex = 1; obscoll.Add(new Item()); ((int)3 =) oscoll.Count(); SelectedIndex = 2; And this should be done in xaml :) Thank you in advance, eza
-
Hi! I have an observablecollection which is instanced in xaml. A listbox is bound to this collection. Binding works great, no problems so far. What I'm struggling with is how to force the listbox via xaml to select the last index available when the observablecollection fires an event. e.g: ((int)2 =) oscoll.Count(); SelectedIndex = 1; obscoll.Add(new Item()); ((int)3 =) oscoll.Count(); SelectedIndex = 2; And this should be done in xaml :) Thank you in advance, eza
Bind ListBox's SelectedIndex to Count property (of the ObservableCollection) . In the binding you would have to use a converter to return a Count - 1 value. Something like this,
<ListView Name="listView" ItemsSource="{Binding}" SelectedIndex="{Binding Path=.Count, Mode=OneWay, Converter={StaticResource SelectedIndexConverter}}" >
<ListView.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=FirstName}"></TextBox>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>The Converter will get the current count value and it will return a Count - 1 value.
public class SelectedIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (object)(System.Convert.ToInt32(value) - 1 );
}public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new Exception("The method or operation is not implemented."); } }