Question I'm failing to bind a brush to the foreground property of a textblock

glasswizzard

Well-known member
Joined
Nov 22, 2019
Messages
126
Programming Experience
Beginner
So I made a class called MyBrushes (stored in a folder called "Classes"). So far it looks like this:

C#:
using System.Windows.Media;

namespace WpfApp1.Classes
{
    public class MyBrushes
    {
        public Brush Brush1 = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00BA00"));
        public Brush Brush2 = new SolidColorBrush((Color) ColorConverter.ConvertFromString("#587DFE"));     
        public Brush Brush3 = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#50EB15"));
        public Brush Brush4 = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#64E2E2"));

        public MyBrushes()
        {         
        }
    }
}

In my MainWindow.xaml.cs I have the class instantiated and I set it to the data context:

C#:
public MainWindow()
        {
            InitializeComponent();
            MyBrushes myBrushes = new MyBrushes();
            DataContext = myBrushes;
        }

Then I bind it in the textblock's attribute:

XML:
<TextBlock Text="0" HorizontalAlignment="Center" FontSize="28" Foreground="{Binding Brush1}"/>

I don't know what I'm doing wrong, but the text is always black. I checked MSDN and the foreground property does take a Brush object so I know it's not that. I know I have to set the datacontext and that's simple to do so it's not that. I'm think maybe I got the syntax wrong perhaps in the actual binding itself?
 
I find it admirable that you've gone ahead and are expanding what you are learning about data binding and are applying it to your UI as well, but it looks like what you are really trying to do is "theming" and "skinning". This blog post will help you a lot because it the appropriate WPF way instead of your current approach:
 
Back
Top Bottom