wpf - 单向绑定时禁用自定义 WPF 控件
问题描述
我有一个自定义 WPF 控件(使用 UserControl 作为基础),它公开了可绑定的属性(使用 DependencyProperty)。当属性之一是单向绑定时,我想禁用此控件中的编辑。
public partial class OnOffControl : UserControl
{
...
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register(
"IsChecked",
typeof(bool?),
typeof(OnOffControl),
...
public bool? IsChecked
{
get
{
return (bool?)GetValue(IsCheckedProperty);
}
set
{
SetValue(IsCheckedProperty, value);
}
}
使用点
<DataGridTemplateColumn Width="40" Header="State">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<UIUtil:OnOffControl
IndicatorType="SwitchIndicator"
IsChecked="{Binding Value, Mode=OneWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
因此,当 IsChecked 是单向绑定时,我想禁用 OnOffControl 中的编辑。如何检测控件内部的属性绑定是 OneWay 然后禁用编辑?
解决方案
您可以检查是否存在 Binding 并在 PropertyChangedCallback 中获取 Binding 的属性:
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register(
nameof(IsChecked),
typeof(bool?),
typeof(OnOffControl),
new PropertyMetadata(IsCheckedPropertyChanged));
public bool? IsChecked
{
get { return (bool?)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
private static void IsCheckedPropertyChanged(
DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var control = (OnOffControl)o;
var binding = control.GetBindingExpression(IsCheckedProperty)?.ParentBinding;
var enabled = false;
if (binding != null)
{
enabled = binding.Mode == BindingMode.TwoWay
|| binding.Mode == BindingMode.OneWayToSource;
}
control.IsEnabled = enabled;
}
推荐阅读
- containers - 如何优雅地分离奇点容器?
- tcpdf - 如何防止 TCPDF 中的 MultiCell 分页
- java - 使用 selenium webdriver 时如何从列中获取特定值并将其插入字段中
- reporting-services - SSRS - 更改 x 轴以同时显示日期和小时数 - 问题
- hibernate - Grails 域映射到不需要的 _IDX 列
- python - 过滤中间模型并使用它来修改模型的查询集
- php - Laravel Voyager 属于多个关系显示“未找到结果”
- ios - 使用平移手势选择多个 tableview 单元格
- docker - Keycloak 在 Docker 中引发 SSL 连接错误
- typescript - 从 .jar 文件夹添加主类