我使用一个数据模板(datatemplate)来将ComboBox中的一些项目可视化, ItemsSource绑定到ObservableCollection。为了简单起见,假设我将人员放入ObservableCollection中:
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}
我的数据模板看起来像这样:
<DataTemplate TargetType="{x:Type Person}">
<StackPanel Orientation="Horizontal">
<TextSearch.Text>
<MultiBinding StringFormat="{} {0} {1}">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
</MultiBinding>
</TextSearch.Text>
<TextBlock Text="{Binding FirstName}" Margin="2,0" />
<TextBlock Text="{Binding LastName}"/>
</StackPanel>
</DataTemplate>
现在我想在ComboBox中启用全名自动完成,但不想在我的人员类上引入第三个属性。因此,我不想在ComboBox上使用TextSearch.TextPath属性,而是想将每个ComboBoxItem的TextSearch.Text属性绑定到DataTemplate中。 不幸的是,当我这样做时(使用MultiBinding和StringFormat,通过Snoop测试),绑定值仅为我的StackPanel注册,但使用Snoop(很棒的工具)我发现这个stackpanel只是一些进一步的ComboBoxItemTemplate的内容,它放置了另一个边框等等,最后在我的外部StackPanel周围放置了一个ComboBoxItem标签。因此,TextSearch.Text设置无效,因为它必须在创建的ComboBoxItem中设置,而不是在其他地方设置。
现在的问题是:如何仅使用XAML样式和控件模板将DataTemplate中的TextSearch.Text属性传播到周围的ComboBoxItem?解决方案可能修改ComboBox和ComboBoxItem的默认ControlTemplates以及我的自定义(Item-)DataTemplate,但不使用任何Code-Behind,或者至少不要太多。也许附加行为也可以,但我几乎确定必须有一种方法使其正常工作,而不需要TemplateBinding或RelativeSource-stuff……当然,解决方案必须使我的键盘选择和文本完成工作,例如,当列表包含Hans Josef和Hans Peter时,输入“Hans”应该自动建议Hans Josef,而输入“Hans P”足够快时应该自动建议Hans Peter。
有什么解决方案吗?