如何将文本修饰添加到列表视图行?

时间:2015-05-01 03:03:38

标签: c# wpf listview

我的listview itemssource是一个名为Person的对象,它显示Person.Name。我想为特定行应用文本修饰:

strikeThrough = new TextDecoration(TextDecorationLocation.Strikethrough, new Pen(Brushes.Black, 1), 0, TextDecorationUnit.FontRecommended, TextDecorationUnit.FontRecommended);

我想根据Person.Name划掉整行。

如何将此装饰应用于列表视图中的选定项目?

1 个答案:

答案 0 :(得分:1)

您应该将自定义ItemTemplate添加到ListView,然后创建绑定到Person对象的某个属性。该属性可以根据人名返回TextDecoration。方法如下:

<强> Person.cs:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PersonFullName { get { return FirstName + " " + LastName; } }

    public TextDecorationCollection PersonTextDecorations
    {
        get
        {
            if (FirstName == "George")
            {
                return new TextDecorationCollection() 
                    { 
                        new TextDecoration
                            (
                            TextDecorationLocation.Strikethrough,
                            new Pen(Brushes.Red, 1), 
                            0, 
                            TextDecorationUnit.Pixel, 
                            TextDecorationUnit.Pixel
                            ) 
                    };
            }
            else
            {
                return null;
            }
        }
    }
}

<强> MainWindow.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<Person> persons = new List<Person>();
        persons.Add(new Person() { FirstName = "Barack", LastName = "Obama" });
        persons.Add(new Person() { FirstName = "George", LastName = "Bush" });
        persons.Add(new Person() { FirstName = "Bill", LastName = "Clinton" });
        persons.Add(new Person() { FirstName = "Ronald", LastName = "Reagan" });
        this.myListView.ItemsSource = persons;
    }
}

<强> MainWindow.xaml:

    <ListView x:Name="myListView">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding PersonFullName}" TextDecorations="{Binding PersonTextDecorations}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

<强>输出:

enter image description here