如何更改特定单元格的DataGridTemplateColumn DataTemplate元素的属性

时间:2019-07-02 11:52:20

标签: c# wpf datagrid datagridtemplatecolumn

我之前创建的DataGrid出现问题。 DataGrid显示有关项目任务的信息。现在,我必须使开始日期和结束日期列可编辑。为此,我使用以下代码更改了DataGridTextColumn:

<DataGridTemplateColumn Header="Start"  Width="100" CanUserReorder="True">
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <DatePicker 
        x:Name="DpStartDate" 
        SelectedDate="{Binding PlannedStart, StringFormat=\{0:dd.MM.yyyy\}}" 
        IsEnabled="False"/>
    </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

到目前为止,一切都很好。现在的问题是,如果任务处于正确的状态以更改日期,我必须检查每一行。如果是这样,我必须启用DatePicker。在后面的代码中,我这样尝试过:

for(int _i = 0; _i < DgvProjectTaskList.Items.Count; _i++)
{
      switch (((TaskListViewModel) DgvProjectTaskList.Items[_i]).Task.State)
      {
         case TaskStates.InWork:
         {
            DatePicker _dpStart = DgvProjectTaskList.Columns[4].GetCellContent(_i) as DatePicker;
            _dpStart.IsEnabled = false;
            DatePicker _dpEnd = DgvProjectTaskList.Columns[5].GetCellContent(_i) as DatePicker;
            _dpEnd.IsEnabled = true;
            break;
         }
         case TaskStates.Done:
         {
            DatePicker _dpStart = DgvProjectTaskList.Columns[4].GetCellContent(_i) as DatePicker;
            _dpStart.IsEnabled = false;
            DatePicker _dpEnd = DgvProjectTaskList.Columns[5].GetCellContent(_i) as DatePicker;
            _dpEnd.IsEnabled = false;
            break;
         }
         default:
         {
            DatePicker _dpStart = DgvProjectTaskList.Columns[4].GetCellContent(_i) as DatePicker;
            _dpStart.IsEnabled = true;
            DatePicker _dpEnd = DgvProjectTaskList.Columns[5].GetCellContent(_i) as DatePicker;
            _dpEnd.IsEnabled = true;
            break;
         }
      }
}

问题在于“ GetCellContent”每次都返回null。所以我的问题是如何分别更改每一行中的DatePicker? 预先感谢!

2 个答案:

答案 0 :(得分:2)

我认为您应该可以这样做:

var contentPresenter = DgvProjectTaskList.Columns[4].GetCellContent(item);
var datePicker = VisualTreeHelper.GetChild(contentPresenter, 0) as DatePicker;
datePicker.IsEnabled = true;

GetCellContent()返回一个ContentPresenter,第一个孩子是DatePicker


如果您尝试这样做,它将起作用:

  foreach (var item in DgvProjectTaskList.Items)
  {
    bool enable = item.Task.State != TaskStates.Done;

    var contentPresenter = Data.Columns[4].GetCellContent(item );
    var picker = VisualTreeHelper.GetChild(contentPresenter, 0) as DatePicker;
    picker.IsEnabled = enable;
    contentPresenter = Data.Columns[5].GetCellContent(item );
    picker = VisualTreeHelper.GetChild(contentPresenter, 0) as DatePicker;
    picker.IsEnabled = enable;
  }

答案 1 :(得分:2)

我终于通过在ViewModel中创建布尔并将其绑定到DatePicker的isEnabled属性来解决了这个问题。