簡體   English   中英

WPF組合框中的所有顏色,沒有一種

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM