WPF:将组合框中的DisplayMemberPath绑定到Item

Jef*_*ney 11 data-binding wpf combobox

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

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

<ComboBox ItemsSource="{Binding CurrentDocument.Pages}"
    DisplayMemberPath="???"
    SelectedItem="{Binding CurrentPage, Mode=TwoWay}">
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

和我一起到目前为止?所有这一切都很好,除了我需要DisplayMemberPath显示"Page 1","Page 2"等.....

我尝试创建一个这样的转换器:

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

并尝试将DisplayMemberPath绑定到它,如下所示:

DisplayMemberPath="{Binding RelativeSource={RelativeSource Self}, Path=Index, Converter={StaticResource pgTitleConv}}"
Run Code Online (Sandbox Code Playgroud)

但它仍然不会出现在组合框文本中!

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

Bot*_*000 23

试试这个:

<ComboBox.ItemTemplate>
  <DataTemplate>
    <TextBlock Text="{Binding Converter={StaticResource pgTitleConv}}"/>
  </DataTemplate>
</ComboBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

在您的valueconverter中,如果可以访问页面集合,则可以使用CurrentDocument.Pages.IndexOf(value)来获取绑定项目的索引.我确信有更好的方法.