How do I stop property values from flowing down the element tree in xaml?
-
20-09-2019 - |
Question
Let's say I have some Control that has been disabled. It contains a bunch of elements, but I want one of those child elements to remain enabled.
Something like this:
<ContentControl IsEnabled="False">
<Border>
<Button Content="Button" IsEnabled="True"/>
</Border>
</ContentControl>
So in this example, the Button's IsEnabled="True" setting gets overridden by its parent. Is there a way of stopping this from happening?
This seems like a strange thing to be doing, but I have a situation where, when a Control is disabled and a user mouses down on it, I still want an event to be triggered.
I read in WPF Unleashed that wrapping something in a Frame control, "..isolates the content from the rest of the UI [and] properties that would normally be inherited down the element tree stop when they reach the Frame", but wrapping the Button in the example above in a Frame doesn't work.
Am I on the wrong track here?
Solution
that's not inheritance, it's composition
the containing control is disabled, thus all of its contained controls are disabled
enable the container and the control that you want, and disable the other controls
OTHER TIPS
If you can inherit the button (or any control that you need), you can replace the CoerceValue to avoid this behavior (in fact, I think IsEnabled should work like IsChecked, being a bool?, where null means use the parent value, any specific value should be kept... but as that's not the behavior, using this solution will solve the problem):
public sealed class InheritedButton:
Button
{
static InheritedButton()
{
InheritedButton.IsEnabledProperty.OverrideMetadata
(
typeof(InheritedButton),
new FrameworkPropertyMetadata
(
true,
null,
_CoerceIsEnabled
)
);
}
private static object _CoerceIsEnabled(DependencyObject source, object value)
{
return value;
}
}