What is the simplest way to get a WPF resource from code?
I need to disable a text box in a WPF form if a checkbox in the same window is checked. I have wired the checkbox to an event handler in code-behind. The event handler disables the checkbox and changes its background to a light gray, to indicate that the control is disabled:
private void OnCheckBoxChecked(object sender, RoutedEventArgs e)
{
MyTextBox.IsEnabled = false;
MyTextBox.Background = (Brush)FindResource("DisabledControlBackgroundBrush");
}
The disabled control background color is defined as a resource in a resource dictionary that is imported into the WPF window. I tested the resource by setting the textbox background in XAML, and the resource works fine.
I also know the event handler is working, because it disables the text box when the checkbox is clicked.
My problem is that the event handler isn't changing the Background property as it should. I suspect that there is a problem with my call to FindResource, but I am not getting an exception, and the Output window has nothing on it.
So, how do I get this resource from code and apply it to my text box? Thanks for your help.
Best Answer
David. I've put together a sample window that does this using triggers on the
TextBox.Style
:You can't use a
Trigger
to change another control's properties, but you can use them to change a control's properties based on something else, like aDataContext
or another control.Each control can have a
Triggers
collection, but this can only containEventTriggers
. In aStyle
you can use plainTrigger
which can be used to control animation, as well asDataTrigger
, which I've used in this sample to control theTextBox
settings based on the properties of theCheckBox
.Notice that I've also used a
Setter
outside of theTriggers
collection to set the default value, and I don't need a secondSetter
for when theCheckBox
is not checked -- it just goes back to the "default" state.edit - how to change background of disabled
TextBox
I do this in Blend, but if you don't have Blend you can of course put the XAML in directly. This has to do with controls states. As the
TextBox
transitions amongNormal
,MouseOver
, andDisabled
, you can animate changes to the appearance. In this case we use an animation of virtually zero duration, so the change is immediate.Add the following to the
StackPanel
: