Binding to the selected item in an ItemsControl

Posted by Jensen on Stack Overflow See other posts from Stack Overflow or by Jensen
Published on 2010-01-26T19:27:44Z Indexed on 2010/04/03 2:03 UTC
Read the original article Hit count: 956

Filed under:
|
|
|

I created a custom ComboBox as follows: (note, code is not correct but you should get the general idea.) The ComboBox contains 2 dependency properties which matter: TitleText and DescriptionText.

<Grid>
  <TextBlock x:Name="Title"/>
  <Grid x:Name="CBG">
    <ToggleButton/>
    <ContentPresenter/>
    <Popup/>
  </Grid>
</Grid>

I want to use this ComboBox to display a wide range of options. I created a class called Setting which inherits from DependencyObject to create usable items, I created a DataTemplate to bind the contents of this Settings object to my ComboBox and created a UserControl which contains an ItemControl which has as a template my previously mentioned DataTemplate. I can fill it with Setting objects.

<DataTemplate x:Key="myDataTemplate">
  <ComboBox TitleText="{Binding Title}" DescriptionText="{Binding DescriptionText}"/>
</DataTemplate>

<UserControl>
  <Grid>
    <StackPanel Grid.Column="0">
      <ItemsControl Template="{StaticResource myDataTemplate}">
        <Item>
          <Setting Title="Foo" Description="Bar">
            <Option>Yes</Option><Option>No</Option>
          </Setting>
        </Item>
      </ItemsControl>
    </StackPanel>
    <StackPanel Grid.Column="1">
      <TextBlock x:Name="Description"/>
    </StackPanel>
  </Grid>
</UserControl>

I would like to have the DescriptionText of the selected ComboBox (selected by either the IsFocus of the ComboBox control or the IsOpen property of the popup) to be placed in the Description TextBlock in my UserControl.

One way I managed to achieve this was replacing my ItemsControl by a ListBox but this caused several issues: it always showed a scrollbar even though I disabled it, it wouldn't catch focus when my popup was open but only when I explicitly selected the item in my ListBox, when I enabled the OverridesDefaultStyle property the contents of the ListBox wouldn't show up at all, I had to re-theme the ListBox control to match my UserControl layout...

What's the best and easiest way to get my DescriptionText to show up without using a ListBox or creating a custom Selector control (as that had the same effect as a ListBox)?

The goal at the end is to loop through all the items (maybe get them into an ObservableCollection or some sort and to save them into my settings file.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about wpf