2009-07-27 97 views
11

好吧,这有点奇怪,但这基本上是我需要做的。我有一个绑定到Document对象的WPF控件。 Document对象具有一个Pages属性。所以在我的ViewModel中,我有一个CurrentDocument属性和一个CurrentPage属性。WPF:在组合框中绑定DisplayMemberPath到项目

现在,我有一个组合框,我已经绑定到CurrentDocument.Pages属性并更新CurrentPage属性。

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

到目前为止我和谁?所有这一切都只是我需要的DisplayMemberPath显示“1”,“第2页”等精细.....

我试图创建一个转换器像这样:

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

而且尝试的DisplayMemberPath绑定到它是这样的:

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

但它仍然不会在组合框中的文本显示出来!

有没有“索引”属性,但我不知道如何做到这一点...如何访问该组合框绑定到项目的索引... ??????

回答

24

试试这个:

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

,并在您valueconverter,如果你可以访问网页集合,你可以使用CurrentDocument.Pages.IndexOf(值)来获取绑定项的索引。我确信有更好的方法。

+0

工作就像我的情况魅力。 – JohnathanKong 2010-03-12 15:17:30

0

好的,感谢Botz3000我想出了如何做到这一点。 (这是有点虚张声势,但它工作正常。)

突然,它来到我身上:Page对象有一个Document对象!卫生署!

所以,我PageTitleConvert只是做这个:

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; 
}