2009-07-27 45 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; 
}