In Windows Presentation Foundation (WPF), how do you set the Background color of a TextBox or other element from the C# Code-Behind? Normally we set this in the XAML, and it doesn’t change throughout the program. What if we need to change at run time? What if a user clicks a button to change the background color of something on the GUI? Suppose we have options or preferences in our program?
BrushConverter
Below is a screenshot and the code for the project.
<Window x:Class="BindingCodeBehindPreferences.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:BindingCodeBehindPreferences" mc:Ignorable="d" WindowStartupLocation="CenterScreen" Title="BindingCodeBehindPreferences" Height="150" Width="360"> <StackPanel> <TextBlock Name="txtBlk" Background="White" Margin="6,2,2,2">Set Background from Code-Behind to #98FB98</TextBlock> <Label Name="lbl" Background="White" Margin="6,2,2,2">Set Background from Code-Behind to #FAEBD7</Label> <Ellipse Name="ell" Margin="2,2,2,2" Height="10" Width="10" Fill="White"/> <TextBox Name="txtBox" Height="26" Width="100" Margin="6,2,2,2" Background="White"/> </StackPanel> </Window>
Below is the C# code behind. Notice that we can set the color with a string. We could have read that string from a SQLite database and set it in the code behind.
using System.Windows; using System.Windows.Media; namespace BindingCodeBehindPreferences { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var bc = new BrushConverter(); txtBlk.Background = (Brush)bc.ConvertFrom("#98FB98"); lbl.Background = (Brush)bc.ConvertFrom("#FAEBD7"); ell.Fill = (Brush)bc.ConvertFrom("#0000FF"); txtBox.Background = (Brush)bc.ConvertFrom("#FF00AB"); txtBox.Background = new SolidColorBrush(Colors.LightPink); } } }