我创造了自己的组合框样式以及stylign组合框项目。下拉列表需要显示一些带按钮的项目,而其他没有我的项目的项目是动态创建的,如下所示:
ComboBoxItem typeItem = new ComboBoxItem();
typeItem.Content = "Test";
typeItem.Tag = i;
MyCombobox.Items.Add(typeItem);
我的问题是如何将这种风格应用于某些项目,而不是其他项目,我的两个组合框架是否在下面?
<Style x:Key="{x:Type ComboBoxItem}" TargetType="{x:Type ComboBoxItem}">
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Top" />
<Setter Property="MinHeight" Value="{DynamicResource ResourceKey=MinimumIteractSizeDips}" />
<Setter Property="MinWidth" Value="{DynamicResource ResourceKey=MinimumIteractSizeDips}" />
<Setter Property="Foreground" Value="Black"/>
</Style>
<Style x:Key="MyComboBoxItem" TargetType="{x:Type ComboBoxItem}">
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Top" />
<Setter Property="MinHeight" Value="{DynamicResource ResourceKey=MinimumIteractSizeDips}" />
<Setter Property="MinWidth" Value="{DynamicResource ResourceKey=MinimumIteractSizeDips}" />
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBoxItem">
<Grid>
<Label Content="{TemplateBinding Content}" Foreground="Black" Background="White" Height="26" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="0" Grid.Column="0"/>
<Button Grid.Column="2" Grid.Row="0" Content="Settings" Height="23" HorizontalAlignment="Left" Margin="2" Name="PositionSettings" VerticalAlignment="Center" Width="57"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
答案 0 :(得分:0)
检查StyleSelector课程。
public class MyStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
var element = container as FrameworkElement;
var myVm = item as MyViewModel;
if(myVm.EditMode)
return element.FindResource("TemplateWithButtons") as DataTemplate
return element.FindResource("TemplateNormal") as DataTemplate
}
}
并在xaml中为您的选择器定义资源
<MyStyleSelector x:Key="myStyleSelector"/>
并将其应用于您的组合框。
<ComboBox StyleSelector="{StaticResource myStyleSelector}"/>
顺便说一句。 x:与TargetType
类型相同的密钥是多余的。
最后注意:您不应该为此覆盖样式。你想要的是DataTemplate和DataTemplate选择器。此外,您不应该将Content(类型对象)绑定到标签文本(类型字符串),ContentPresenter是这里的方式。