简体   繁体   中英

WPF All colors in combobox without one

I need to put all colors from class Colors to combobox, but without Transparent. I know how it made, but it is additionally condition - I have to do all using binding.

I have:

<Window.Resources>
    <ObjectDataProvider  ObjectInstance="{x:Type Colors}" MethodName="GetProperties" x:Key="colorPropertiesOdp" />
</Window.Resources>

 <ComboBox ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" DisplayMemberPath="Name"  SelectedValuePath="Name"/>

and it provide all colors. But I don't know how I can delete Transparent.

Thanks for help!

You can assign this to a CollectionViewSource and Filter the transparent.

<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;
        }
    }
}

I can't think of a pure XAML solution to this problem. Even a CollectionViewSource with a filter will require a function in either the codebehind or the viewmodel depending on your approach. So, you can save some code on both ends and just filter the list on the backend before its attached to the combobox. For the sake of simplicity the code below uses the window's codebehind instead of a viewmodel.

On the backend:

public static IEnumerable<String> ColorsWithoutTransparent
{
    get
    {
        var colors = typeof (Colors);
        return colors.GetProperties().Select(x => x.Name).Where(x => !x.Equals("Transparent"));
    }
}

Modified XAML (Take note of the added 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM