Albert Gao
Albert Gao

Reputation: 3769

Why does it throws a Arg_ InvalidCastException when I cast a color resources in WP7?

I work on a project target on Windows Phone 7.5 and above. I define a color resources in App.xaml and use it as a global resource. And When I use it in code-behind, it throws me a error.

The Resource in XAML:

<SolidColorBrush x:Key="BackgroundColor" Color="#FFF6F6F6"/>

The invoke in C#

    private void BuildApplicationBar()
    {
        ApplicationBar = new ApplicationBar();
        ApplicationBar.BackgroundColor = (Color)Application.Current.Resources["BackgroundColor"];
    }

The error happens when I try cast the resource: [Arg_InvalidCastException]

Arguments: Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=4.0.50829.0&File=mscorlib.dll&Key=Arg_InvalidCastException

Why and how to resolve it, I did check that the type of AppBar's bgcolor is a Color,how could this happen when I do the cast?

Upvotes: 0

Views: 609

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39007

You're declaring the resource as a Brush, yet you're casting it to Color. It can't possibly work.

Try this instead:

private void BuildApplicationBar()
{
    ApplicationBar = new ApplicationBar();
    ApplicationBar.BackgroundColor = ((SolidColorBrush)Application.Current.Resources["BackgroundColor"]).Color;
}

Upvotes: 1

Related Questions