[英]WPF All colors in combobox without one
我需要将所有颜色从“颜色”类添加到组合框,但不设置“透明”。 我知道它是如何制作的,但这是附加条件-我必须使用绑定来完成所有操作。
我有:
<Window.Resources>
<ObjectDataProvider ObjectInstance="{x:Type Colors}" MethodName="GetProperties" x:Key="colorPropertiesOdp" />
</Window.Resources>
<ComboBox ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" DisplayMemberPath="Name" SelectedValuePath="Name"/>
它提供所有颜色。 但是我不知道如何删除透明。
感谢帮助!
您可以将其分配给CollectionViewSource并过滤透明对象。
<Window.Resources>
<ObjectDataProvider ObjectInstance="{x:Type Colors}" MethodName="GetProperties" x:Key="colorPropertiesOdp" />
<CollectionViewSource x:Key="FilterCollectionView" Filter="CollectionViewSource_Filter" Source="{StaticResource colorPropertiesOdp}" />
</Window.Resources>
<ComboBox ItemsSource="{Binding Source={StaticResource FilterCollectionView}}" DisplayMemberPath="Name" SelectedValuePath="Name"/>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
{
System.Reflection.PropertyInfo pi = (System.Reflection.PropertyInfo)e.Item;
if (pi.Name == "Transparent")
{
e.Accepted = false;
}
else
{
e.Accepted = true;
}
}
}
我想不出一个纯粹的XAML解决方案来解决这个问题。 即使是带有过滤器的CollectionViewSource,根据您的方法,也需要在代码隐藏或视图模型中使用一个函数。 因此,您可以在两端保存一些代码,只需在后端列表附加到组合框之前对其进行过滤。 为了简单起见,下面的代码使用背后的窗口代码而不是视图模型。
在后端:
public static IEnumerable<String> ColorsWithoutTransparent
{
get
{
var colors = typeof (Colors);
return colors.GetProperties().Select(x => x.Name).Where(x => !x.Equals("Transparent"));
}
}
修改的XAML(注意添加的Window DataContext):
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox Margin="50" ItemsSource="{Binding ColorsWithoutTransparent}"/>
</Grid>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.