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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Is there some documentation about this? Without knowing such details, I feel like a monkey typing jibberish.
The question about built in converters has already been answered here - stackoverflow.com/questions/505397/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.