WPF中如何基于DataGrid项完整DataContext动态切换单元格模板?
解决方案:修复ContentControl的Content绑定,确保DataContext正确传递
你的问题核心是ContentControl未正确设置Content属性——仅设置DataContext不足以让模板内部的绑定关联到当前ProcessingJob实例。WPF中ContentControl的ContentTemplate是基于其Content属性渲染的,当Content为null时,模板内的绑定会丢失上下文。
步骤1:修正ContentControl的绑定
将CellTemplate里的ContentControl修改为:
<ContentControl Style="{StaticResource selectableContentStyle}" Content="{Binding}"/>
移除原有的DataContext="{Binding}",改用Content="{Binding}"——ContentControl会自动将Content作为模板的DataContext。
步骤2:确保属性变更通知正常
检查ProcessingJob类是否正确实现INotifyPropertyChanged接口,且Status和Progress属性变更时触发事件:
public class ProcessingJob : INotifyPropertyChanged { private JobStatus _status; public JobStatus Status { get => _status; set { _status = value; OnPropertyChanged(nameof(Status)); } } private int _progress; public int Progress { get => _progress; set { _progress = value; OnPropertyChanged(nameof(Progress)); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
若未实现该接口,不仅模板切换不会响应Status变化,Progress的更新也无法同步到进度条。
补充:DataTemplateSelector不生效的原因
DataTemplateSelector的SelectTemplate方法仅在控件初始化(或ItemsSource刷新)时调用一次,不会监听属性变化,因此用Style+DataTrigger的方案是正确方向,只是之前未正确配置ContentControl。
修改后的完整CellTemplate代码
<DataGridTemplateColumn Header="Status"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <ContentControl Style="{StaticResource selectableContentStyle}" Content="{Binding}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn>
修改后,模板切换会正常响应Status变化,进度条也能正确绑定到Progress属性。
内容的提问来源于stack exchange,提问作者azulBonnet
相关产品推荐
相关产品推荐

