0

I have a itemscontrol as below

   <StackPanel>
        <ItemsControl Name="PlannerItemControl" Grid.Row="0" Grid.Column="0">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid Name="MainGrid" Style="{StaticResource VisibleKey}">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*" />
                            <RowDefinition Height="35" />
                        </Grid.RowDefinitions>
                        <Label Grid.Row="1" Grid.Column="2" Name="lblTimeText" Content="{Binding ID}" HorizontalAlignment="Center"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
    <Label Grid.Row="1" Grid.Column="2" Name="lblTime2" Content="{Binding ID}" HorizontalAlignment="Center"/>

Is it possible to retrieve the value of ID from the itemscontrol outside of the itemscontrol? Basically I want the value of Label lblTimeText in label lblTime2. Please help.

user2837961
  • 1,505
  • 3
  • 27
  • 67
  • Have you set ID to use NotifyPropertyChanged in your ViewModel? then your binding should work – VisualBean Apr 22 '15 at 08:41
  • @VisualBean Yes I have. It works as expected in lblTimeText but please note that itemsouce of PlannerItemControl is a ObservableCollection set in the code. – user2837961 Apr 22 '15 at 08:48
  • Ahh so your looking for a selectedItem.ID or are there multiple lbltime2? – VisualBean Apr 22 '15 at 08:56
  • @VisualBean Yes I am looking for selectedItem.ID outside the itemscontrol. There is only one lblTime2- don't understand 'are there mutiple lblTime2' – user2837961 Apr 22 '15 at 08:59
  • ItemsControl doesn't track selectedItem - thus I thought you might have multiple labels to fill (wierd, but what the heck :)) - see this answer http://stackoverflow.com/questions/18456836/gettting-selected-item-in-itemscontrol – VisualBean Apr 22 '15 at 09:00
  • @VisualBean Thanks for that. Assuming that I changing the ItemsControl to ListBox, how would lblTime2 refer to selecteditem? – user2837961 Apr 22 '15 at 09:18

1 Answers1

1

The ItemsControl does not track SelectedItem - instead use a ListBox. (The selectedItem should be the same type as your collection items).

To track a selectedItem you need to bind the selectedItem property of the listbox to a property in your ViewModel

<Listbox ItemsSource="{Binding Path=YourCollection}" SelectedItem="{Binding YourItem}">

(remember INotifyChanged)

and then bind that item.id to your label

 <Label Grid.Row="1" Grid.Column="2" Name="lblTime2" Content="{Binding YourItem.ID}" HorizontalAlignment="Center"/>
VisualBean
  • 4,908
  • 2
  • 28
  • 57