基本上我只是在 SL3 ComboBox 中寻找“SelectedItemTemplate”。不幸的是,那不存在。
我想要的是 SelectedItem 看起来像这样:值
下拉框中的项目看起来像这样:价值+额外信息
后者很容易通过使用 ItemTemplate 完成,但 SelectedItem 看起来也是如此。我该如何预防/解决这个问题?
基本上我只是在 SL3 ComboBox 中寻找“SelectedItemTemplate”。不幸的是,那不存在。
我想要的是 SelectedItem 看起来像这样:值
下拉框中的项目看起来像这样:价值+额外信息
后者很容易通过使用 ItemTemplate 完成,但 SelectedItem 看起来也是如此。我该如何预防/解决这个问题?
您可以通过创建自己的 SelectionBoxItemTemplate 附加属性,然后为 ComboBox 定义一个新的样式/控件模板,该模板在内容呈现器中为选择框区域使用该模板。
这是一个合适的附加属性:
public class ComboBoxExt
{
public static DataTemplate GetSelectionBoxItemTemplate(DependencyObject obj)
{
return (DataTemplate) obj.GetValue(SelectionBoxItemTemplateProperty);
}
public static void SetSelectionBoxItemTemplate(DependencyObject obj, DataTemplate value)
{
obj.SetValue(SelectionBoxItemTemplateProperty, value);
}
public static readonly DependencyProperty SelectionBoxItemTemplateProperty =
DependencyProperty.RegisterAttached("SelectionBoxItemTemplate", typeof (DataTemplate), typeof (ComboBoxExt),
new PropertyMetadata(null));
}
要更新 ComboBox 控件模板,请ContentPresenter
在一个名为的元素中查找名为的元素(您可以在此处ContentPresenterBorder
找到 ComboBox 的默认样式)。您需要删除 ContentPresenter 的名称(否则 ComboBox 将通过代码显式设置其属性的值,而忽略您设置的数据绑定)。
调整后的控件模板中的 ContentPresenter 元素应如下所示:
<ContentPresenter Margin="{TemplateBinding Padding}"
Content="{Binding Path=SelectedItem, RelativeSource={RelativeSource TemplatedParent}}"
ContentTemplate="{Binding (a:ComboBoxExt.SelectionBoxItemTemplate), RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
</ContentPresenter>
最后,要使用它,您可以执行以下操作:
<ComboBox
Style="{StaticResource MyAdjustedComboBoxStyle}"
ItemTemplate="{StaticResource MyDropDownAreaTemplate}"
Behaviors:ComboBoxExt.SelectionBoxItemTemplate="{StaticResource MySelectionAreaTemplate}">
你在找.
SelectionBoxItemTemplate
吗?
SelectionBoxItemTemplate
在 Silverlight4 中可用,但无法从代码隐藏设置此属性的值,因为它是只读属性。它也不是依赖属性,因此无法使用comboBox.SetValue()
方法设置值。关于如何在代码隐藏中为该属性赋值的任何想法?