C# WPF SfDataGrid的IsHidden绑定值更新后不生效问题
问题解决方法
1. 修复ViewModel属性的冗余代码
你的UserExpertValues属性存在冗余操作:SetProperty方法本身已包含字段赋值和属性变更通知逻辑,无需手动重复赋值与触发事件。修改后的属性代码如下:
public bool UserExpertValues { get => _userExpertValues; set => SetProperty(ref _userExpertValues, value); }
(注:若你的SetProperty是实现INotifyPropertyChanged的标准方法,它会自动在值变更时触发PropertyChanged事件)
2. 修正列的绑定上下文问题
SfDataGrid的列对象(如GridTextColumn)不属于Visual Tree范畴,默认无法直接继承ViewModel的DataContext,导致属性更新后绑定无法同步。可通过以下两种方式解决:
方式一:使用RelativeSource绑定到DataGrid的DataContext
修改列的IsHidden绑定,通过RelativeSource定位到SfDataGrid的上下文:
<chart:GridTextColumn MappingName="{Binding ColumnsText[2], Converter={StaticResource TranslationConverter}}" IsHidden="{Binding DataContext.UserExpertValues, RelativeSource={RelativeSource AncestorType={x:Type syncfusion:SfDataGrid}}, Mode=TwoWay}"> </chart:GridTextColumn>
方式二:使用ElementName绑定
给SfDataGrid设置名称,通过ElementName绑定上下文:
<syncfusion:SfDataGrid x:Name="MyDataGrid" ...> <syncfusion:SfDataGrid.Columns> <chart:GridTextColumn MappingName="{Binding ColumnsText[2], Converter={StaticResource TranslationConverter}}" IsHidden="{Binding DataContext.UserExpertValues, ElementName=MyDataGrid, Mode=TwoWay}"> </chart:GridTextColumn> </syncfusion:SfDataGrid.Columns> </syncfusion:SfDataGrid>
3. 验证属性变更通知的正确性
确保ViewModel正确实现INotifyPropertyChanged接口,SetProperty方法逻辑无误,示例实现如下:
public class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
内容的提问来源于stack exchange,提问作者jokipu
相关产品推荐
相关产品推荐

