开发者

How to bind SelectedItem (from a ListBox) to a Variable?

I'm working on my first WP7 App and this problem causes me some headache.

I've a ListBox defined like this

    <ListBox Grid.Row="1" ItemsSource="{Binding MyItemList}" SelectedItem="{Binding MySelectedItem}">
        <ListBox.ItemTemplate>
            <DataTemplate >
                <StackPanel>
                    <TextBlock Text="{Binding Name}" FontSize="35" />
                    <TextBlock Text="{Binding Details}" FontSize="15"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Binding the ItemsSource works fine, but the MySelectedItem-Property doesn't get updated when selecting an item. Is this functio开发者_StackOverflown not implemented (like in WPF) or am I just doing something? :-)


Just use -

SelectedItem="{Binding MySelectedItem, Mode=TwoWay}" and it should be fine.


You might have to set IsSynchronizedWithCurrentItem="True" for your ListBox.


This is my workaround.. I hope someone will post a more elegant solution.

XAML:

 <ListBox Name="DecksListBox" ItemsSource="{Binding MyItemsList}"
          SelectionChanged="UpdateSelectedItem"

Code-behind:

    private void UpdateSelectedItem(object sender, SelectionChangedEventArgs e)
    {
        // Ignore if there is no selection
        if (DecksListBox.SelectedIndex == -1)
            return;
        App.ViewModel.MySelectedItem = App.ViewModel.MyItemsList[DecksListBox.SelectedIndex];
    }

Maybe this might help someone in the meantime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜