将WPF Datagrid的行颜色绑定到可观察集合中的项的属性

时间:2016-12-27 18:40:01

标签: wpf binding datagrid itemssource

我希望有人可以帮助我。我有一个MVVMLight应用程序,其中我有一个可观察的对象集合,在我的视图模型中,绑定到WPF DataGrid的ItemsSource属性。现在,只要名为“TaskAssignmentStatus”的特定值更改为observable集合中的任何项目,我就想更改行背景颜色。

但是我收到的XAML Parse错误如下:

{“在使用ItemsSource时操作无效。请改为使用ItemsControl.ItemsSource访问和修改元素。”}

我已经阅读了关于该错误我能找到的所有内容但是我无法看到如何应用我从迄今为止给出的答案中学到的任何内容到我的具体情况。我是WPF和databiding的新手,所以任何帮助都会非常感激。谢谢!

我的视图模型中的相关代码如下:

//Contains the actual tasks on the currently selected team member's    
//work-list
public ObservableCollection<WorklistTask> TasksForSelectedTeamMember
{
    get { return _tasksForSelectedTeamMember; }
    set
    {
        if (value != null)
        {
            _tasksForSelectedTeamMember = value;
            RaisePropertyChanged("TasksForSelectedTeamMember");
        }
    }
}

以下是view-model中我的observable集合中类型的类定义:

public class WorklistTask : ICloneable
{
    #region Fields

    private int _taskId;
    private int _activityId;
    private string _activityName;
    private string _activityStatus;
    private string _taskAssignDate;
    private string _activityStartDate;
    private string _activityDueDate;
    private string _caseStartDate;
    private string _caseDueDate;
    private int _caseId;
    private string _caseType;

    //an enum which indicates whether or not the task has been reassigned 
    private WorkListTaskAssignmentStatus _taskAssignmentStatus;

    private int _sourceTaskId;
    private bool _selectedByUserInUI = false;


    #endregion

    #region Constructors

    public WorklistTask() { }

    #endregion

    #region Properties

    [DisplayName("Task Assignment Status")]
    public WorkListTaskAssignmentStatus TaskAssignmentStatus
    {
        get { return _taskAssignmentStatus; }
        set { _taskAssignmentStatus = value; }
    }


    public int TaskId
    {
        get { return _taskId; }
        set { _taskId = value; }
    }


    public int ActivityId
    {
        get { return _activityId; }
        set { _activityId = value; }
    }

    [DisplayName("Activity Name")]
    public string ActivityName
    {
        get { return _activityName; }
        set { _activityName = value; }
    }
    [DisplayName("Activity Status")]
    public string ActivityStatus
    {
        get { return _activityStatus; }
        set { _activityStatus = value; }
    }
    [DisplayName("Task Assigned Date")]
    public string TaskAssignDate
    {
        get { return _taskAssignDate; }
        set { _taskAssignDate = value; }
    }
    [DisplayName("Activity Start Date")]
    public string ActivityStartDate
    {
        get { return _activityStartDate; }
        set { _activityStartDate = value; }
    }
    [DisplayName("Activity Due Date")]
    public string ActivityDueDate
    {
        get { return _activityDueDate; }
        set { _activityDueDate = value; }
    }
    [DisplayName("Case Start Date")]
    public string CaseStartDate
    {
        get { return _caseStartDate; }
        set { _caseStartDate = value; }
    }
    [DisplayName("Case Due Date")]
    public string CaseDueDate
    {
        get { return _caseDueDate; }
        set { _caseDueDate = value; }
    }

    [DisplayName("Case Id")]
    public int CaseId
    {
        get { return _caseId; }
        set { _caseId = value; }
    }
    [DisplayName("Case Type")]
    public string CaseType
    {
        get { return _caseType; }
        set { _caseType = value; }
    }


    public int SourceTaskId
    {
        get { return _sourceTaskId; }
        set { _sourceTaskId = value; }
    }

    public bool SelectedByUserInUI
    {
        get { return _selectedByUserInUI; }
        set { _selectedByUserInUI = value; }
    }

    #endregion

    #region Methods

    public object Clone()
    {
        WorklistTask newWorklistTask = (WorklistTask)this.MemberwiseClone();
        newWorklistTask.ActivityName = string.Copy(ActivityName);
        newWorklistTask.ActivityStatus = string.Copy(ActivityStatus);
        newWorklistTask.TaskAssignDate = string.Copy(TaskAssignDate);
        newWorklistTask.ActivityStartDate = string.Copy(ActivityStartDate);
        newWorklistTask.ActivityDueDate = string.Copy(ActivityDueDate);
        newWorklistTask.CaseStartDate = string.Copy(CaseStartDate);
        newWorklistTask.CaseDueDate = string.Copy(CaseDueDate);
        newWorklistTask.CaseType = string.Copy(CaseType);

        return newWorklistTask;
    }

    #endregion
}

这是枚举:

public enum WorkListTaskAssignmentStatus
{
    Automatic,
    Added,
    Removed,
    DeleteLocal
}

以下是我尝试格式化的数据网格的XAML:

<DataGrid x:Name="WorklistOfSelectedTeamMember"
          ItemsSource="{Binding TasksForSelectedTeamMember, Mode=TwoWay,   
          UpdateSourceTrigger=PropertyChanged}"                 
          AutoGeneratingColumn="GenerateColumnsForWorklist"                                   
          IsReadOnly="True"
          FontWeight="Normal"
          FontSize="13" 
          SelectionMode="Extended"
          AlternatingRowBackground="LightGray"
          Grid.Column="0"
          Grid.ColumnSpan="2"
          Grid.Row="3" 
          Margin="0,0,5,0"
          HorizontalScrollBarVisibility="Auto"
          Height="150"
          Style="{StaticResource DataGridColoring}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <cmd:EventToCommand Command="{Binding 
                WorklistTaskSelectionChangedCommand}" 
                CommandParameter="{Binding SelectedItems, 
                ElementName=WorklistOfSelectedTeamMember}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding TaskAssignmentStatus}" 
                 Value="Automatic">  
                    <Setter Property="Background" Value="Transparent"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding TaskAssignmentStatus}" 
                 Value="Removed">
                    <Setter Property="Background" Value="#C4FF0000"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding TaskAssignmentStatus}" 
                 Value="Added">
                     <Setter Property="Background" Value="#00FF7F"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding TaskAssignmentStatus}" 
                 Value="DeleteLocal">
                     <Setter Property="Background" Value="#00FFFFFF"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>                            
</DataGrid>

2 个答案:

答案 0 :(得分:0)

你改变背景颜色的代码似乎很好,它应该可以工作。

您提到的错误字符串与此无关,这意味着您正在尝试以某种方式直接从DataGrid DataGrid.ItemsSource

的ItemsSource属性添加/删除元素

您不能使用ItemsSource直接修改您必须使用该集合的元素。

答案 1 :(得分:0)

您可以通过将隐式RowStyle添加到DataGrid的资源字典中来消除您所获得的错误:

<DataGrid x:Name="WorklistOfSelectedTeamMember"
          ItemsSource="{Binding TasksForSelectedTeamMember, Mode=TwoWay,   
          UpdateSourceTrigger=PropertyChanged}"                                                   
          IsReadOnly="True"
          FontWeight="Normal"
          FontSize="13" 
          SelectionMode="Extended"
          AlternatingRowBackground="LightGray"
          Grid.Column="0"
          Grid.ColumnSpan="2"
          Grid.Row="3" 
          Margin="0,0,5,0"
          HorizontalScrollBarVisibility="Auto"
          Height="150">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand Command="{Binding 
                WorklistTaskSelectionChangedCommand}" 
                CommandParameter="{Binding SelectedItems, 
                ElementName=WorklistOfSelectedTeamMember}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding TaskAssignmentStatus}" 
                 Value="Automatic">
                    <Setter Property="Background" Value="Transparent"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding TaskAssignmentStatus}" 
                 Value="Removed">
                    <Setter Property="Background" Value="#C4FF0000"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding TaskAssignmentStatus}" 
                 Value="Added">
                    <Setter Property="Background" Value="#00FF7F"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding TaskAssignmentStatus}" 
                 Value="DeleteLocal">
                    <Setter Property="Background" Value="#00FFFFFF"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
</DataGrid>

另请注意,如果您希望在运行时将ObservableCollection中项的TaskAssignmentStatus属性的值设置为新值时更改行的背景颜色,则WorklistTask类应实现INotifyPropertyChanged接口并引发TaskAssignmentStatus属性的setter中的PropertyChanged事件。