I'm learning WPF and I have made a simple program to better understand a few things and I got stuck. In this program, I want to select the color in the ComboBox and change the foreground color of the TextBlock above it according to the selected. I've tried data binding but it didn't work (I believe it is because I use DataTemplate for the ComboBox), so I tried do it by an event handler but I don't quite get how the SelectedItem property works. Here's the XAML code:
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="My First GUI" Height="450" Width="800">
<StackPanel Orientation="Vertical">
<TextBlock Text="Sample Text" FontSize="50" FontWeight="Bold" Name="title" HorizontalAlignment="Center" Margin="30"/>
<ComboBox Name="comboBox" SelectionChanged="comboBox_SelectionChanged" HorizontalAlignment="Center" Width="300">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Name="rect" Fill="{Binding Name}" Width="24" Height="24"/>
<TextBlock Text="{Binding Name, StringFormat={} {0}}" FontSize="20"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Window>
And here the code behind:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//Combobox data setup
comboBox.ItemsSource = typeof(Colors).GetProperties();
}
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
title.Foreground = new SolidColorBrush(comboBox.SelectedItem as Color);//This line doesn't work
}
}
}
So I want to ask about all possible approaches to this problem and which is the best approach to complete it. Thank you very much!