簡體   English   中英

單向綁定時禁用自定義 WPF 控件

[英]Disable custom WPF control when binding is oneway

我有一個自定義 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 中的編輯。 一個go怎么檢測控件里面的屬性綁定是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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM