我有一个UserControl
带有控件的窗口。
我想为此添加Enabled
属性,以控制所选控件 UserControl
的属性状态。IsReadOnly
我该怎么做?
谢谢 :-)
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); }
}