ListViewItem 不使用绑定的 IValueConverter 更改前景色

发布于 2024-12-22 10:58:10 字数 4287 浏览 3 评论 0原文

我的麻烦是我希望我的 WPF ListView 根据绑定到 ListViewItems 的项目以不同的颜色显示。下面是重现该问题的所有代码。该应用程序具有“有库存”或“无库存”的小部件。如果有库存,ListView 中应该有绿色文本,否则为红色。着色由我的 BoolToColorConverter 处理(将 Widget.InStock 转换为 Colors.Green 或 Colors.Red)。断点确保 Convert() 被命中。我可能做了一些明显错误的事情,但我不知所措,因为硬编码前景色按预期工作。提前致谢。

MainWindow.xaml

<Window x:Class="ListViewItemColors.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ListViewItemColors" Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <local:WidgetsViewModel />
</Window.DataContext>
<Window.Resources>
    <local:BoolToColorConverter x:Key="BoolToColor" />
</Window.Resources>
<DockPanel >
    <ListView ItemsSource="{Binding Path=Widgets }">
        <ListView.View>
            <GridView>
                <GridViewColumn Width="150" Header="Widget Name">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=Name}" Foreground="{Binding Path=InStock, Converter={StaticResource BoolToColor}}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Width="50" Header="Size" DisplayMemberBinding="{Binding Size}"></GridViewColumn>
                <GridViewColumn Width="75" Header="In Stock?" DisplayMemberBinding="{Binding InStock}"></GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</DockPanel>

BoolToColorConverter.cs

public class BoolToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var val = (bool)value;
        return val ? Colors.Green : Colors.Red;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

WidgetsViewModel.cs

public class WidgetsViewModel
{
    public WidgetsViewModel()
    {
        Widgets = new Widgets
                      {
                          new Widget {InStock = true, Name = "Flipper", Size = 10},
                          new Widget {InStock = false, Name = "Gizmo", Size = 6},
                          new Widget {InStock = true, Name = "Gizmo", Size = 8},
                          new Widget {InStock = true, Name = "Whirlygig", Size = 15},
                          new Widget {InStock = false, Name = "Gutter", Size = 1},
                          new Widget {InStock = false, Name = "Gutter", Size = 2}
                      };
    }

    public Widgets Widgets { get; set; }
}

Widget.cs

public class Widget : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name == value) return;
            _name = value;
            OnPropertyChanged("Name");
        }
    }

    private int _size;
    public int Size
    {
        get { return _size; }
        set
        {
            if (_size == value) return;
            _size = value;
            OnPropertyChanged("Size");
        }
    }

    private bool _inStock;
    public bool InStock
    {
        get { return _inStock; }
        set
        {
            if (_inStock == value) return;
            _inStock = value;
            OnPropertyChanged("InStock");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }
}

Widgets.cs

    public class Widgets : ObservableCollection<Widget> { }

My trouble is that I want my WPF ListView to display ListViewItems in different colors, according to the items bound to them. Below is all the code to repro the problem. The app has Widgets that are either "in stock" or not. If they're in stock, they should have green text in the ListView, otherwise red. The coloring is handled by my BoolToColorConverter (transforming Widget.InStock to Colors.Green or Colors.Red). Breakpoints assure me Convert() is being hit. I'm probably doing something obviously wrong, but I'm at a loss since hard-coding the Foreground color works as expected. Thanks in advance.

MainWindow.xaml

<Window x:Class="ListViewItemColors.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ListViewItemColors" Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <local:WidgetsViewModel />
</Window.DataContext>
<Window.Resources>
    <local:BoolToColorConverter x:Key="BoolToColor" />
</Window.Resources>
<DockPanel >
    <ListView ItemsSource="{Binding Path=Widgets }">
        <ListView.View>
            <GridView>
                <GridViewColumn Width="150" Header="Widget Name">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=Name}" Foreground="{Binding Path=InStock, Converter={StaticResource BoolToColor}}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Width="50" Header="Size" DisplayMemberBinding="{Binding Size}"></GridViewColumn>
                <GridViewColumn Width="75" Header="In Stock?" DisplayMemberBinding="{Binding InStock}"></GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</DockPanel>

BoolToColorConverter.cs

public class BoolToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var val = (bool)value;
        return val ? Colors.Green : Colors.Red;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

WidgetsViewModel.cs

public class WidgetsViewModel
{
    public WidgetsViewModel()
    {
        Widgets = new Widgets
                      {
                          new Widget {InStock = true, Name = "Flipper", Size = 10},
                          new Widget {InStock = false, Name = "Gizmo", Size = 6},
                          new Widget {InStock = true, Name = "Gizmo", Size = 8},
                          new Widget {InStock = true, Name = "Whirlygig", Size = 15},
                          new Widget {InStock = false, Name = "Gutter", Size = 1},
                          new Widget {InStock = false, Name = "Gutter", Size = 2}
                      };
    }

    public Widgets Widgets { get; set; }
}

Widget.cs

public class Widget : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name == value) return;
            _name = value;
            OnPropertyChanged("Name");
        }
    }

    private int _size;
    public int Size
    {
        get { return _size; }
        set
        {
            if (_size == value) return;
            _size = value;
            OnPropertyChanged("Size");
        }
    }

    private bool _inStock;
    public bool InStock
    {
        get { return _inStock; }
        set
        {
            if (_inStock == value) return;
            _inStock = value;
            OnPropertyChanged("InStock");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }
}

Widgets.cs

    public class Widgets : ObservableCollection<Widget> { }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稳稳的幸福 2024-12-29 10:58:10

TextBlock.Foreground 属性采用画笔,而不是颜色。更改您的转换器,使其返回 SolidColorBrush,例如:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var val = (bool)value;
    return new SolidColorBrush(val ? Colors.Green : Colors.Red);
} 

The TextBlock.Foreground property takes a Brush, not a Color. Change your converter so that it returns a SolidColorBrush, e.g.:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var val = (bool)value;
    return new SolidColorBrush(val ? Colors.Green : Colors.Red);
} 
爱本泡沫多脆弱 2024-12-29 10:58:10

这对我有用:

enter code here
 <ListView.ItemContainerStyle>
           <Style TargetType="ListViewItem">
                <Setter Property="Foreground" 
                 Value="{Binding FColor,Mode=OneWay,UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ColorConverter}}"/>   
           </Style>
        </ListView.ItemContainerStyle>
        <ListView.View>
            <GridView>                    
                <GridViewColumn Header="Category" 
                   DisplayMemberBinding="{Binding CatDesc,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
                                  Width="450"/>                    
            </GridView>
        </ListView.View>  

This worked for me:

enter code here
 <ListView.ItemContainerStyle>
           <Style TargetType="ListViewItem">
                <Setter Property="Foreground" 
                 Value="{Binding FColor,Mode=OneWay,UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ColorConverter}}"/>   
           </Style>
        </ListView.ItemContainerStyle>
        <ListView.View>
            <GridView>                    
                <GridViewColumn Header="Category" 
                   DisplayMemberBinding="{Binding CatDesc,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
                                  Width="450"/>                    
            </GridView>
        </ListView.View>  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文