2

Consider the following XAML code:

    <StackPanel>
        <ListBox x:Name="lbColor">
            <ListBoxItem Content="Blue"/>
            <ListBoxItem Content="Green"/>
            <ListBoxItem Content="Yellow"/>
        </ListBox>
        <TextBlock>
            <TextBlock.Text>
                <Binding ElementName="lbColor" Path="SelectedItem.Content"/>
            </TextBlock.Text>
            <TextBlock.Background>
                <Binding ElementName="lbColor" Path="SelectedItem.Content"/>
            </TextBlock.Background>
        </TextBlock>
    </StackPanel>

I understand how Text property binding works. Internally it is converted to something like:

textBlock.Text = lbColor.SelectedItem.Content;

But how Background is bound to the same source? This code:

textBlock.Background = lbColor.SelectedItem.Content;

is incorrect. How can it work? BTW, it works and shows correct background color.

The only way I see, is to get System.Windows.Media.Colors property with given name, create SolidColorBrush from it and assign to Background property. But there is nothing in the code which points to this path.

Alex F
  • 42,307
  • 41
  • 144
  • 212

1 Answers1

6

This works because there is a built in conversion that allows WPF to convert from a String to a Brush (which is the required type of the Background property).

If you look at the MSDN documentation for Brush, you can see that it is decorated with a TypeConverter attribute that specifies a converter of type BrushConverter.

For general information about type converters, have a read of this article

Steve Greatrex
  • 15,789
  • 5
  • 59
  • 73
  • Thanks. Is there some documentation about this? Without knowing such details, I feel like a monkey typing jibberish. – Alex F Nov 15 '10 at 11:54
  • 1
    The question about built in converters has already been answered here - http://stackoverflow.com/questions/505397/built-in-wpf-ivalueconverters – EightyOne Unite Nov 15 '10 at 12:09