WPF组合框中的所有颜色都没有

WPF All colors in combobox without one

我需要将 class 颜色中的所有颜色放入组合框,但没有透明。我知道它是如何制作的,但它还有一个条件 - 我必须使用绑定来完成所有操作。

我有:

<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 也需要代码隐藏或视图模型中的函数,具体取决于您的方法。因此,您可以在两端保存一些代码,并在将列表附加到组合框之前在后端过滤列表。为了简单起见,下面的代码使用 window 的代码隐藏而不是视图模型。

在后端:

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>