0
votes

I'm starting with WPF and I have this pretty easy question:

I have a TextBlock and a Listbox that share the same DataContext. The ItemsSource of the ListBox is set to point to a property of the DataContext that its an ObservableCollection. I want that the TextBlock to contain the selected item of the Listbox. Some code:

View view = new View();
view.DataContext = new ViewModel();
view.Show();
<TextBlock Name="textBox1" Grid.Row="0" Grid.Column="0" Margin="1" Text="{Binding ¿xxx?}"></TextBlock>
<ListBox Name="listBox1" Grid.Row="1" Grid.ColumnSpan="2" Margin="1" ItemsSource="{Binding Model.BinariesToDeploy}" IsSynchronizedWithCurrentItem="True" />

Hope its clear.

2

2 Answers

2
votes

If you actually want to use the synchronization you need to bind to the current item of the collection which will be set by the ListBox or any other control which has IsSynchronizedWithCurrentItem set to true, to do so use the /:

<TextBlock Text="{Binding Model.BinariesToDeploy/}" />

When the source is a collection view, the current item can be specified with a slash (/). For example, the clause Path=/ sets the binding to the current item in the view. When the source is a collection, this syntax specifies the current item of the default collection view.

The current item is managed by the CollectionView which is a layer on top of your original collection, CollectionViews can also be used for filtering, sorting and grouping.


An example:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Page.Resources>
        <x:Array x:Key="items" Type="{x:Type Label}">
            <Label Content="Apple" Tag="Fruit"/>
            <Label Content="Pear" Tag="Fruit"/>
            <Label Content="Orange" Tag="Fruit"/>
            <Label Content="Lime" Tag="Fruit"/>
            <Label Content="Tomato" Tag="Vegetable"/>
            <Label Content="Radish" Tag="Vegetable"/>
            <Label Content="Lettuce" Tag="Vegetable"/>
        </x:Array>
    </Page.Resources>
    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
        <StackPanel>
            <ListBox IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource items}}"/>
            <!-- Binds to CurrentItem.Content -->
            <ContentControl Content="{Binding /Content,Source={StaticResource items}}"/>
        </StackPanel>
    </ScrollViewer>
</Page>
1
votes

try something like this

Text = "{Binding ElementName=listBox1, Path=SelectedValue.Content}"