C# 在WPF中将SelectedValue设置为Collection[Index]

C# 在WPF中将SelectedValue设置为Collection[Index],c#,wpf,binding,C#,Wpf,Binding,我正在使用下面的XAML填充列表框。我已经将DataContext设置为静态类(建筑)中的静态集合(立面) 我总是将当前立面的索引作为建筑的属性存储在“立面”集合中:CurrentElevationIndex 现在我想将SelectedValue设置为Building.Elevations[Building.CurrentElevationIndex] 我不需要改变它。这是一次性的事情。我只需要在窗口启动时设置它 <ListBox x:Name="PlanElevationsLis

我正在使用下面的
XAML
填充
列表框
。我已经将
DataContext
设置为静态类(建筑)中的静态集合(立面)

我总是将当前立面的索引作为建筑的属性存储在“立面”集合中:CurrentElevationIndex

现在我想将
SelectedValue
设置为
Building.Elevations[Building.CurrentElevationIndex]

我不需要改变它。这是一次性的事情。我只需要在窗口启动时设置它

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

如果希望它是一次性的,并在窗口开始时设置,则此时必须知道Building.CurrentElevationIndex。那么,为什么不将其设置为
Building.Elevations[0]
呢。(假设加载时默认为第0个索引)

XAML

<ListBox x:Name="PlanElevationsList"
         DataContext="{x:Static building:Building.Elevations}"
         ItemsSource="{Binding}"
         SelectedValue="{x:Static building:Building.SelectedElevation}"/>
您还可以在窗口上设置
x:Name
,并使用ElementName:

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

....

谢谢Rohit,如果我在Window.cs本身而不是建筑中定义
SelectedElevation
属性,该怎么办。在这种情况下,如何设置selectedvalue?
<ListBox x:Name="PlanElevationsList"
         DataContext="{x:Static building:Building.Elevations}"
         ItemsSource="{Binding}"
         SelectedValue="{x:Static building:Building.SelectedElevation}"/>
SelectedValue="{Binding SelectedElevation, RelativeSource={RelativeSource 
                            FindAncestor, AncestorType=Window}, Mode=OneTime}"
<Window x:Name="myWindow">
   ....
   <ListBox SelectedValue="{Binding SelectedElevation, ElementName=myWindow, 
                                    Mode=OneTime}">