Vahid
Vahid

Reputation: 5454

Set the SelectedValue to Collection[Index] in WPF

I'm using the below XAML to populate a ListBox. I have already set the DataContext to a static collection (Elevations) in a static class (Building).

I'm always storing the index of the current elevation in the Elevations collection as a property of the Building: CurrentElevationIndex

Now I want to set the SelectedValue to Building.Elevations[Building.CurrentElevationIndex]

I don't need it to be changed. It is a one time thing. I only need it to be set when the Window starts.

    <ListBox x:Name="PlanElevationsList"
             DataContext="{x:Static building:Building.Elevations}"
             ItemsSource="{Binding}"
             SelectedValue="">
    </ListBox>

Upvotes: 0

Views: 103

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81313

If you want it to be OneTime and set at window start then Building.CurrentElevationIndex must be known at that time. so, why not to set it like Building.Elevations[0] for instance. (Assuming 0th index will be default at load)

<ListBox x:Name="PlanElevationsList"
         DataContext="{x:Static building:Building.Elevations}"
         ItemsSource="{Binding}"
         SelectedValue="{x:Static building:Building.Elevations[0]}"/>

In case CurrentElevationIndex is not known at startup you can have a wrapper property in class to return that value. However, converter might be a way to go but for OneTime operation seems not a valid approach.

public static string SelectedElevation
{
   get
   {
      return Elevations[CurrentElevationIndex];
   }
}

XAML

<ListBox x:Name="PlanElevationsList"
         DataContext="{x:Static building:Building.Elevations}"
         ItemsSource="{Binding}"
         SelectedValue="{x:Static building:Building.SelectedElevation}"/>

Update for comment:

What if I'm defining the SelectedElevation property in the Window.cs itself not in the building. How can I set the selectedvalue in this case?

You can bind it using RelativeSource with AncestorType set to Window:

SelectedValue="{Binding SelectedElevation, RelativeSource={RelativeSource 
                            FindAncestor, AncestorType=Window}, Mode=OneTime}"

Also you can set x:Name on window and bind using ElementName:

<Window x:Name="myWindow">
   ....
   <ListBox SelectedValue="{Binding SelectedElevation, ElementName=myWindow, 
                                    Mode=OneTime}">

Upvotes: 1

Related Questions