简体   繁体   English

单向绑定时禁用自定义 WPF 控件

[英]Disable custom WPF control when binding is oneway

I have a custom WPF control (using UserControl as base) that exposes a bindable properties (using DependencyProperty).我有一个自定义 WPF 控件(使用 UserControl 作为基础),它公开了可绑定的属性(使用 DependencyProperty)。 I want to disable editing in this control when one of the properties is a oneway binding.当属性之一是单向绑定时,我想禁用此控件中的编辑。

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);
        }
    }

           

Usage point使用点

                        <DataGridTemplateColumn Width="40" Header="State">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <UIUtil:OnOffControl 
                                        IndicatorType="SwitchIndicator"
                                        IsChecked="{Binding Value, Mode=OneWay}"/>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>

So when IsChecked is a oneway binding I want to disable editing in OnOffControl.因此,当 IsChecked 是单向绑定时,我想禁用 OnOffControl 中的编辑。 How does one go about detecting the property binding is OneWay inside of the control and then disable editing?一个go怎么检测控件里面的属性绑定是OneWay然后禁用编辑?

You may check if there is a Binding and get the Binding's properties in a PropertyChangedCallback:您可以检查是否存在 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM