views:

25

answers:

1

Hi all,

I'm trying to bind a property of a resource object to a control (a combo...) - the thing seems to work in the designer, but it is not working at runtime. Just using a simple page with only a button and a combo - resource section:

<UserControl.Resources>
    <LinearGradientBrush x:Key="myBrush" EndPoint="1,0.5" StartPoint="0,0.5">
        <GradientStop Offset="0" Color="{Binding ElementName=w_comboColor, Path=SelectedItem.Content}" />
        <GradientStop  Offset="1" Color="White" />
    </LinearGradientBrush>
</UserControl.Resources>

and the widgets section:

<Button Name="w_button" Grid.Row="0" Width="200" Content="Button" Height="60" HorizontalAlignment="Center"
        Margin="2" VerticalAlignment="Center" Background="{Binding Source={StaticResource myBrush}}">
</Button>

<ComboBox Grid.Row="1" Height="24" HorizontalAlignment="Stretch" Margin="2"
          Name="w_comboColor" VerticalAlignment="Center" SelectedIndex="1" >
    <ComboBox.Items>
        <ComboBoxItem Content="Red" />
        <ComboBoxItem Content="Blue" />
        <ComboBoxItem Content="Green" />
    </ComboBox.Items>
</ComboBox>

changing the value of the SelectedIndex property of the combo, in the designer, makes the button background to change its background color (as expected). If I run the sample, nothing works any more :-\

I tried to force the DataContext of the UserControl and other stuff - nothing happens: at runtime the binding is broken. Any ideas?

A: 

You need to add a ValueConverter to your GradientStop.Color binding to convert from a string to a Color. Your current binding is trying to assign a string to a Color property. I would imagine the designer will do the type conversion for you, just like it would be done in XAML, but that won't happen at runtime. You will need a converter something like this:

public class ColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value == "Red")
            return Colors.Red;
        else if(value == "Blue")
            return Colors.Blue;
        else if(value == "Green")
            return Colors.Green;
    }
}

This definitely is not a complete converter, but it should point you in the right direction.

Stephan
Hi Stephan, many thanks for your answer.Actually I already tried to add a Converter to the Gradient.Stop binding but it gets completely ignored. The only way to use a converter is to bind the Gradient.Stop.Color to a Color DP in the code behind and bind the Combo to that DP with a Converter, that of course converts the string to a Color.Anyway, this is a "workaround" - and sure, it works well :-)But I just wanted to understand how this could be done in "pure XAML", since it could be a good "sample" for other aspects of our infrastrucure to give to our clients.
Ampelio Attanasi