【问题标题】:wpf combobox item template for the selected value and search functionality用于选定值和搜索功能的 wpf 组合框项目模板
【发布时间】:2012-04-18 13:49:04
【问题描述】:

我在我的应用程序中使用了一个组合框,我正在用类似这样的类来填充它:

namespace Foo.Bar{
     public class Item
     {
          public string lastName;
          public string firstName;
          public Foo theMeatyPart;
     }
}

我可以使用 itemTamplate 用“lastName, firstName”填充下拉列表,但随后所选值显示为“Foo.Bar.Item”。如何将相同的模板应用到 selectedItem 并且在不覆盖 Item 的 ToString 方法的情况下让搜索功能正常工作?

这里是 xaml:

<Style x:Key="SearchComboStyle" TargetType="ComboBox">
                <Style.Setters>
                    <Setter Property="Width" Value="150"></Setter>
                </Style.Setters>
            </Style>
            <DataTemplate x:Key="SearchComboItemTemplate" >
                    <TextBlock DataContext="{Binding}">
                            <TextBlock.Text>
                              <MultiBinding StringFormat="{}{0}, {1}">
                                <Binding Path="lastName"/>
                                <Binding Path="firstName"/>
                              </MultiBinding>
                            </TextBlock.Text>
                    </TextBlock>
            </DataTemplate>


<ComboBox  ItemTemplate="{StaticResource SearchComboItemTemplate}" Style="{StaticResource SearchComboStyle}" 
                    ItemsSource="{Binding Path=PhysiciansList, RelativeSource={RelativeSource AncestorType=local:ExamViewerControl, AncestorLevel=1}}"      IsTextSearchEnabled="True" IsTextSearchCaseSensitive="False" IsEditable="True" TextSearch.TextPath="Person.LastName" />         

【问题讨论】:

    标签: wpf combobox


    【解决方案1】:

    UPD:看来你需要设置SelectionBoxItemTemplate

    您可以使用DisplayMemberPathTextSearch.TextPath 来启用搜索,而无需修改ToString()。

    【讨论】:

    • 哎呀。对不起。您使用哪种组合框?可以编辑吗?
    • System.Windows.Controls.ComboBox .NET 4.0
    • AFAIK,您无法更改 ComboBox 可编辑部分中使用的 TextBox 的外观,即您无法应用 DataTemplate。 ComboBox 使用 DisplayMemberPath 或 TextSearch.Path 在嵌套的 TextBox 上设置内容。
    • 我可以对 displaymemberpath 应用相同的多重绑定吗?
    • 很遗憾没有。 WPF 在内部使用临时绑定到路径设置为 DisplayMemberPath(或 PathText)的项目。但是有几种方法可以帮助你。第一个是覆盖 ToString 或添加一个类似于 MultiBinding 的属性。第二个是为 Item 类创建一个视图模型,该类使用附加属性 DisplayValue 包装原始项目。第三个是将您的项目包装到 DependencyObject 中,您可以在其中附加 TextSearch.Text 属性。至于我,如果你不能修改 Item 类,第二种解决方案是最好的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多