如何动态更改ListView项目颜色?

时间:2017-10-25 13:27:59

标签: listview data-binding uwp prism

我正在尝试使用数据绑定来更改某些ListView元素的颜色。 例如,我有一个问题列表。

enter image description here

我需要强调已经回答的问题

enter image description here

我需要在用户做出选择后立即突出显示已回答的问题。 有我的列表项DataTemplate:

    <DataTemplate x:Key="QuestionListDataTemplate">
            <Border Padding="5" BorderThickness="2" BorderBrush="Gray" Background="Transparent">
            <TextBlock FontSize="24" 
                       x:Name="QuestionListDataTemplateText"
                       Foreground="{Binding Color}">
                <Run x:Uid="QuestionsPage/QuestionNumber"/>
                <Run Text="{Binding QuestionNumber}"/>
            </TextBlock>
        </Border>
    </DataTemplate>

Question型号:

public class Question : TemplateQuestion
{
    public string PollId { get; set; }
    public string SelectedAnswerId { get; set; }
    public string UserName { get; set; }

    [Ignore]
    public SolidColorBrush Color { get; set; }

    [Ignore]
    public bool Answered { get; set; }

    [Ignore]
    public List<Answer> Answers { get; set; }

    [Ignore]
    public int QuestionNumber { get; set; }
}

我还尝试使用DataTemplateSelectorIValueConverter更改颜色,但它不起作用。

有没有办法有选择地改变ListView项的风格?

1 个答案:

答案 0 :(得分:2)

我有办法做到这一点。

你应该让问题继承INotifyPropertyChanged,它可以在属性改变时通知xaml。

对于你不能使用转换,这是Xaml不知道属性更新。我写下面的代码。

public class Question : TemplateQuestion, INotifyPropertyChanged
{
    public string PollId { get; set; }
    public string SelectedAnswerId { get; set; }
    public string UserName { get; set; }

    public SolidColorBrush Color
    {
        get { return _color; }
        set
        {
            _color = value;
            OnPropertyChanged();
        }
    }

    public bool Answered { get; set; }

    public List<Answer> Answers { get; set; }

    public int QuestionNumber { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private SolidColorBrush _color;
}
相关问题