处理此类问题的最简单方法通常是附加属性和行为。
DisplayMemberPath
您可以创建两个名为and的附加属性DisplayText
,然后绑定DisplayMemberPath
到父级ComboBox
DisplayMemberPath
并在其中PropertyChangedCallback
设置您自己的绑定,并使用相同的路径为DisplayText
. 之后,您有一个可以绑定到的属性
<Style x:Key="ComboBoxStyle" TargetType="ComboBox">
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ComboBoxItem">
<Setter Property="behaviors:DisplayTextBehavior.DisplayMemberPath"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ComboBox}},
Path=DisplayMemberPath}"/>
<Setter Property="AutomationProperties.AutomationId"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(behaviors:DisplayTextBehavior.DisplayText)}"/>
</Style>
</Setter.Value>
</Setter>
</Style>
显示文本行为
public class DisplayTextBehavior
{
public static DependencyProperty DisplayMemberPathProperty =
DependencyProperty.RegisterAttached("DisplayMemberPath",
typeof(string),
typeof(DisplayTextBehavior),
new FrameworkPropertyMetadata("", DisplayMemberPathChanged));
public static string GetDisplayMemberPath(DependencyObject obj)
{
return (string)obj.GetValue(DisplayMemberPathProperty);
}
public static void SetDisplayMemberPath(DependencyObject obj, string value)
{
obj.SetValue(DisplayMemberPathProperty, value);
}
private static void DisplayMemberPathChanged(object sender, DependencyPropertyChangedEventArgs e)
{
ComboBoxItem comboBoxItem = sender as ComboBoxItem;
string displayMemberPath = GetDisplayMemberPath(comboBoxItem);
comboBoxItem.SetBinding(DisplayTextProperty, new Binding(displayMemberPath));
}
public static DependencyProperty DisplayTextProperty =
DependencyProperty.RegisterAttached("DisplayText",
typeof(string),
typeof(DisplayTextBehavior),
new FrameworkPropertyMetadata(""));
public static string GetDisplayText(DependencyObject obj)
{
return (string)obj.GetValue(DisplayTextProperty);
}
public static void SetDisplayText(DependencyObject obj, string value)
{
obj.SetValue(DisplayTextProperty, value);
}
}