Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Bind DisplayMemberPath in a combobox to the Item

Ok, this is kind of odd but this is basically what I need to do. I have a WPF control that is bound to a Document object. The Document object has a Pages property. So in my ViewModel, I have a CurrentDocument property, and a CurrentPage property.

Now, I have a combobox that I have bound to the CurrentDocument.Pages property and updates the CurrentPage property.

<ComboBox ItemsSource="{Binding CurrentDocument.Pages}"
    DisplayMemberPath="???"
    SelectedItem="{Binding CurrentPage, Mode=TwoWay}">
</ComboBox>

With me so far? All of this is fine except that I need the DisplayMemberPath to show "Page 1", "Page 2", etc.....

I tried creating a converter such as this:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    string pageNumber = "Page {0}";
    return string.Format(pageNumber, value);
}

And tried to bind DisplayMemberPath to it like this:

DisplayMemberPath="{Binding RelativeSource={RelativeSource Self}, Path=Index, Converter={StaticResource pgTitleConv}}"

But it still wouldn't show up in the combo box text!!!

There is no "Index" property but I don't know how to do this...How do I access the index of the item that the combobox is binding to...??????

like image 797
Jeffrey T. Whitney Avatar asked Jul 27 '09 21:07

Jeffrey T. Whitney


1 Answers

try this:

<ComboBox.ItemTemplate>
  <DataTemplate>
    <TextBlock Text="{Binding Converter={StaticResource pgTitleConv}}"/>
  </DataTemplate>
</ComboBox.ItemTemplate>

and in your valueconverter, if you can access the pages collection, you can use CurrentDocument.Pages.IndexOf(value) to get the index of the bound item. I'm sure there is a better way though.

like image 68
Botz3000 Avatar answered Nov 08 '22 03:11

Botz3000