WPF技术问题:自定义MyTextBox无法感知DataGrid单元格选中状态
问题分析与解决方案
核心问题排查与修复步骤:
XAML语法错误修复
你的MyTextBox声明存在语法错误,<custom:MyTextBox="{Binding DataContext,...}缺少属性名称(比如用于显示文本的Text属性),导致控件无法正确初始化。修正后的代码:<custom:MyTextBox Text="{Binding}" IsSelected="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}}, Path=IsSelected, Mode=TwoWay}" HorizontalAlignment="Stretch"/>这里
Text="{Binding}"直接绑定ItemsControl中的字符串项,匹配你“用MyTextBox显示每个字符串”的需求。绑定目标调整
DataGrid默认SelectionUnit为FullRow(整行选中),此时DataGridCell.IsSelected不会被触发更新。因此需要将MyTextBox.IsSelected绑定到父级DataGridRow的IsSelected属性,这样点击DataGrid行时,行的选中状态会同步到控件。验证回调触发
可以在OnIsSelectedPropertyChanged中添加调试输出,确认回调是否正常执行:private static void OnIsSelectedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is MyTextBox myTextBox)) return; // 调试输出,确认状态变更 System.Diagnostics.Debug.WriteLine($"MyTextBox IsSelected: {myTextBox.IsSelected}"); }可选:单元格选中模式配置
如果需要基于单元格选中触发状态变更,可修改DataGrid的SelectionUnit属性:<DataGrid ItemsSource="{Binding SomeData}" SelectionUnit="Cell" PreviewMouseDown="PreviewMouseDown_OperationsTreeViewDataGrid">此时可以恢复绑定
DataGridCell.IsSelected,但这种模式下需要点击单元格而非行来触发选中。
内容的提问来源于stack exchange,提问作者pf12345678910
相关产品推荐
相关产品推荐

