1

我有一个UserControl带有控件的窗口。
我想为此添加Enabled属性,以控制所选控件 UserControl的属性状态。IsReadOnly

我该怎么做?
谢谢 :-)

4

1 回答 1

2

UserControl对于将属性绑定IsReadOnly到父级的每个子控件:

<TextBox IsReadOnly="{Binding Enabled, RelativeSource={RelativeSource AncestorType={x:Type typeOfUserControl}}}">

并为您定义Enabled Dependancy 属性UserControl

您还应该使用 bool 逆转换器将启用到只读逻辑:

[ValueConversion(typeof(bool), typeof(bool))]
    public class InverseBooleanConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            if (targetType != typeof(bool))
                throw new InvalidOperationException("The target must be a boolean");

            return !(bool)value;
        }

        public object ConvertBack(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }

UPD:来自MSDN

您可以使用 as 运算符在兼容的引用类型或可空类型之间执行某些类型的转换。

所以:

public static readonly DependencyProperty EnabledDependencyProperty = 
     DependencyProperty.Register( "Enabled", typeof(bool),
     typeof(UserControlType), new FrameworkPropertyMetadata(true));

public bool Enabled
{
    get { return (bool)GetValue(EnabledDependencyProperty); }
    set { SetValue(EnabledDependencyProperty, value); }
}
于 2013-09-06T07:24:50.650 回答