代码之家  ›  专栏  ›  技术社区  ›  Kubi

根据bool成员对象填充ListBoxItem背景

wpf
  •  2
  • Kubi  · 技术社区  · 15 年前

    我有一个具有布尔成员的类,我想用我的类的集合填充WPF列表框。

    如果我的布尔属性为false,我希望将ListBoxItem的背景设置为其他颜色。使用XAML是否可行?最好的方法是什么?

            class Mi
            {
                public bool mybool{get;set;}
            }
    ...
    List<Mi> mycollection;// the datacontext
    
    3 回复  |  直到 15 年前
        1
  •  3
  •   Travis Heseman    15 年前

    这里有一个用于布尔值的快速通用转换器,允许您为任何类型的属性指定一个值为true,为false指定不同的值。

    [ValueConversion(typeof(bool), typeof(object))]
    public class BooleanValueConverter : IValueConverter
    {
        public object FalseValue { get; set; }
        public object TrueValue { get; set; }
    
        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, 
                              object parameter, CultureInfo culture)
        {
            return (bool)value ? this.TrueValue : this.FalseValue;
        }
    
        public object ConvertBack(object value, Type targetType, 
                                  object parameter, CultureInfo culture)
        {
            return object.Equals(this.TrueValue, value) ? true : false;
        }
    
        #endregion
    }
    

    像这样使用它。

    <SolidColorBrush x:Key="TrueBrush" Color="Green" />
    <SolidColorBrush x:Key="FalseBrush" Color="Red" />
    
    <local:BooleanValueConverter x:Key="BooleanBackground" 
        TrueValue="{StaticResource TrueBrush}" 
        FalseValue="{StaticResource FalseBrush}" />
    
    ...
    
    Background="{Binding Path=Some.PropertyPath.Ending.With.A.Boolean, 
                                 Converter={StaticResource BooleanBackground}}" />
    
        2
  •  4
  •   Matt Hamilton    15 年前

    您可以使用DataTrigger:

    <DataTemplate DataType="{x:Type my:Mi}">
        <Grid>
            <Grid.Style>
                <Style TargetType="Grid">
                    <Setter PropertyName="Background" Value="White" />
    
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding mybool}" Value="True">
                            <Setter PropertyName="Background" Value="Yellow" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            <Grid.Style>
            ... your ListBoxItem contents here ...
        </Grid>
    </DataTemplate>
    
        3
  •  1
  •   benPearce    15 年前

    您可以使用DataTemplateSelector来实现这一点,它有两个具有不同背景的模板。

    更好的方法可能是将background属性绑定到布尔值,并使用一个ivalueConverter,它将返回适当的颜色。

    Background="{Binding Path=mybool, Converter={StaticResource boolToBackgroundConverter}}"