在WPF中更改ListViewItem的前景色 [英] Change the forecolor of a ListViewItem in WPF

查看:121
本文介绍了在WPF中更改ListViewItem的前景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我已经在winForms编程了几年,我最近开始学习WPF。



之前我可以这样做:



Hi,

I have been programming in winForms for a few years and I have recently started to learn WPF.

Previously I could do this:

if (lv.Items[1].Text == "High")
{
     lv.Items[1].SubItems[1].Forecolor = Color.Red;
}





WPF中似乎没有Subitem选项,我该如何实现?



There does not appear to be a Subitem option in WPF, how do i achieve this?

推荐答案

WPF需要思维范式的转变。我八月份开始使用WPF(我还有很多需要学习的东西)。然而,在数据绑定和使用视图模型方面有很多功能。



这里有一些我发现的代码可以让你知道如何去做。起初它看起来像很多额外的工作,但是一旦你习惯它,它就相当不错。







WPF requires a paradigm shift in thinking. I started using WPF back in August (and I still have a lot to learn). However there is a lot of power in databinding and using viewmodels.

Here's some code I found to give you an idea of how to do it. At first it seems like a lot of extra work but once you get used to it, it's pretty great.



public class ItemVM : INotifyPropertyChanged // if you want runtime changes to be reflected in the UI
{
  public string Text {... raise property change in setter }
  public Color BackgroundColor {... ditto... }
}





接下来在DataContext中创建一个这样的对象列表作为属性,以便ListView可以绑定到它。





Next create a list of such objects as a property in your DataContext so that your ListView can bind to it.

// e.g. MainWindow
    public IEnumerable<ItemVM> Items { get; set; }



现在您需要做的就是将ListView绑定到此集合并连接


Now all you need to do is bind your ListView to this collection and wire up the

DataContext of the UI properly
       <ListView x:Name="MyListView" ItemsSource="{Binding Items}" HorizontalContentAlignment="Stretch">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Text}">
                    <TextBlock.Background>
                        <SolidColorBrush Color="{Binding BackgroundColor}"/>
                    </TextBlock.Background>
                    </TextBlock>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button Click="Button_Click" Content="Go PaleGreen"/>





现在改变背景颜色很容易。只需将相应ItemVM对象的属性设置为所需的颜色即可。例如将所有项目设置为PaleGreen





Now changing the background color is easy. Just set the property of the corresponding ItemVM object to the Color you want. e.g. to set all items to go PaleGreen

private void Button_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in Items)
            item.BackgroundColor = Colors.PaleGreen;
    }


这篇关于在WPF中更改ListViewItem的前景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆