DataContext
因为ComboBoxItem
是某个集合的对象。如我所见,Separator
每次当集合的源项为空时,都会应用您的模板。如果您知道集合中有固定数量的空值项(例如 1 个),则可以编写Converter
.
这里有一个例子:
主窗口.xaml
<Window x:Class="ComboBoxWithSeparator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ComboBoxWithSeparator"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<local:MyConverter x:Key="MyConverter" />
<Style TargetType="{x:Type ComboBoxItem}" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
<Setter Property="HorizontalAlignment">
<Setter.Value>
<MultiBinding Converter="{StaticResource MyConverter}">
<Binding />
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ComboBox}" Path="ItemsSource" />
</MultiBinding>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="{x:Null}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBoxItem}">
<Separator HorizontalAlignment="Stretch" IsEnabled="False"/>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="HorizontalAlignment" Value="Stretch" />
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<ComboBox ItemsSource="{Binding}"
Width="250"
Height="25"/>
</Grid>
</Window>
主窗口.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<string> a = new List<string>()
{
"one",
"two",
"three",
"four",
"five",
null,
"seven",
"eight",
"nine",
"ten"
};
DataContext = a;
}
}
public class MyConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string s = (string)values[0];
IEnumerable<string> array = (IEnumerable<string>)values[1];
if (s == null)
return HorizontalAlignment.Stretch;
foreach (string item in array)
{
if (s == item)
return HorizontalAlignment.Left;
if (item == null)
return HorizontalAlignment.Right;
}
return HorizontalAlignment.Left;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
结果:
