0

我有一个自定义 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 然后禁用编辑?

4

1 回答 1

2

您可以检查是否存在 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;
}
于 2021-06-15T13:28:31.800 回答