Reputation: 1253
I have a UserControl
window with controls on it.
I would like to add Enabled
property for this UserControl
which controls states of IsReadOnly
property of selected controls.
How can I do it?
Thank you :-)
Upvotes: 1
Views: 51
Reputation: 7092
for each child control in UserControl
bind IsReadOnly
property to parent:
<TextBox IsReadOnly="{Binding Enabled, RelativeSource={RelativeSource AncestorType={x:Type typeOfUserControl}}}">
and define Enabled
Dependancy property for you UserControl
.
you should also use bool inverse converter to convert enable-to-readonly logic:
[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: From MSDN
You can use the as operator to perform certain types of conversions between compatible reference types or nullable types.
So:
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); }
}
Upvotes: 2