WPF:将ComboBox中的DisplayMemberPath绑定到Item

11

好的,这有点奇怪,但基本上是我需要做的事情。我有一个绑定到文档对象的WPF控件。文档对象有一个页面属性。因此在我的ViewModel中,我有一个CurrentDocument属性和一个CurrentPage属性。

现在,我有一个下拉框,它绑定到CurrentDocument.Pages属性并更新CurrentPage属性。

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

到目前为止还可以理解吗?所有的东西都很好,除了我需要DisplayMemberPath来显示"Page1"、"Page2"等等...

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

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

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

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

2个回答

24

试试这个:

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

在您的值转换器中,如果您可以访问页面集合,您可以使用CurrentDocument.Pages.IndexOf(value)获取绑定项的索引。虽然我相信还有更好的方法。


1
可以运行,但使用转换器会影响性能。我改用绑定的StringFormat特性,例如<TextBlock Text="{Binding StringFormat={}{0:Page\: #0}}" />。 - user755404
@Darren 只是好奇,性能差别有多大?你是如何衡量的?格式字符串中的页面索引在哪里? - Botz3000
他的示例显示他正在格式化一个int值(页码/索引)"string.Format(pageNumber, value);"。你的示例表明,你不需要提供元素名称(Path=)来获取int值。因此,使用绑定的字符串格式化选项在其前面添加“Page”文本是一种简单的方法(我曾经使用“Week x”)。 - user755404
性能:使用自己的格式化函数来获取绑定值将减少代码量。我可能错了,但我认为调用和执行外部值转换器会增加更多的代码。我赞成你的回答,因为它展示了你不需要元素名称,这是让我困惑的事情。 - user755404
@Darren 更多的代码并不一定意味着更差的性能。但是,如果只使用StringFormat,你如何获取页面在其父集合中的索引?我的意思是,我尽可能地喜欢使用StringFormat,但对于这种情况,它无法真正替代转换器。 - Botz3000

0

好的,感谢Botz3000,我弄清楚了如何做到这一点。(有点奇怪,但它运行良好。)

突然间,我想到了:页面对象有一个文档对象!!噢!!

所以,我的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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接