views:

100

answers:

1

I downloaded the Microsoft Visual Studio 2010 Express for Windows Phone and I wrote a simple application to make a first test of the emulator. In this application I have only a button with the property Content binded to a string called ButtonText and with the property Background binded to a SolidColorBrush named FillColor. I handled the Click event with this code:

    void MyButton_Click(object sender, RoutedEventArgs e)
    {
        if (toggle == true)
        {
            ButtonText = "Blue";
            FillColor = new SolidColorBrush(Colors.Blue);
        }
        else
        {
            ButtonText = "Red";
            FillColor = new SolidColorBrush(Colors.Red);
        }
        toggle = !toggle;
    }

Unfortunately this doesn't work. While the Content of the Button changes each time the button is pressed, I cannot say the same for the Background which remains at the same color.
Could you tell me what is wrong? Thank you.

I also post the XAML:

    <Grid x:Name="ContentGrid" Grid.Row="1">
        <Button Name="MyButton" Width="300" Height="300"
                Content="{Binding Path=ButtonText}" 
                Background="{Binding Path=FillColor}" />
    </Grid>
+1  A: 

The issue is with the use of "new" in the line:

FillColor = new SolidColorBrush(Colors.Blue);

Using the "new" operation breaks the data binding that was previously set up. Try using the following instead:

FillColor.Color = Colors.Blue;

Replace both the changes to Blue and to Red and that should do the trick.

HTH!
Chris

Chris Koenig
Thank you for your answer. FillColor's type is not Color, but SolidColorBrush. If I convert it to Color it didn't work because Background's type is not Color.Moreover, I don't agree with you when you say that the "new" operation breaks the data binding, in fact the same solutions works perfectly in a silverlight web site.
Maurizio Reginelli
If you notice in my response, I suggested you change the value of FillColor's Color property, not the FillColor property itself. In my recreation of your issue that fixed the basic problem. I have experienced this same issue with ObservableCollection where newing up an instance inside your code after databinding it will in fact break the binding. I can provide complete code samples to show this in more detail if you're interested...
Chris Koenig
Thank you again Chris. I'm interested to your code sample. You can find my e-mail in my profile. I'll be glad of your help if you send me the code samples.
Maurizio Reginelli