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

时间:2009-07-27 21:41:56

标签: wpf data-binding combobox

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

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

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

到目前为止我?所有这一切都很好,除了我需要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);
}

并尝试将DisplayMemberPath绑定到它:

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

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

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

2 个答案:

答案 0 :(得分:23)

试试这个:

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

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

答案 1 :(得分:0)

好的,感谢Botz3000,我想出了如何做到这一点。 (这有点像wiggy,但它运行正常。)

突然,它来找我:Page对象有一个Document对象!! DOH !!

所以,我的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;
}
相关问题