views:

2686

answers:

2

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...??????

+2  A: 

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.

Botz3000
worked like a charm for my situation.
JohnathanKong
A: 

Ok, Thanks to Botz3000 I figured out how to do this. (It's a bit wiggy, but it works fine.)

Suddenly, it came to me: the Page object has a Document object!! Doh!!

So, my PageTitleConvert just does this:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value != null)
    {
        ImGearPage page = (ImGearPage)value;
        ImGearDocument doc = page.Document;
        int pageIndex = doc.Pages.IndexOf(page);
        pageIndex++;
        return string.Format("Page {0}", pageIndex);
    }
    return null;
}
Jeffrey T. Whitney