DataContext
爲ComboBoxItem
是一些收集的對象。正如我所看到的,您的Separator
模板將在每當收集源的項目爲空時應用。如果您知道集合中存在固定數量的空值項目(例如1),則可以編寫Converter
。
下面的例子:
MainWindow.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>
MainWindow.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();
}
}
而結果:
![ComboBox items are aligned to the right after the separator](https://i.stack.imgur.com/stiQq.png)
我想你Ç找不到具體的元素,所以我建議你使用StyleSelector並且自己檢查元素在代碼中的位置(在null之前或之後) – 2012-08-01 03:34:44
我不太確定,因爲我對wpf很陌生。怎麼做? – DEN 2012-08-01 04:47:41