Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a decimal value in XAML?

I'm able to declare an integer or double value in xaml. However, I can't add a decimal value. It builds ok, but then I get:

System.Windows.Markup.XamlParseException: The type 'Decimal' was not found.

Here's the xaml code:

<UserControl.Resources>
    <system:Int32 x:Key="AnIntValue">1000</system:Int32><!--Works!-->
    <system:Double x:Key="ADoubleValue">1000.0</system:Double><!--Works!-->
    <system:Decimal x:Key="ADecimalValue">1000.0</system:Decimal><!--Fails at runtime-->
</UserControl.Resources>

Here's how I'm declaring the system namespace:

xmlns:system="clr-namespace:System;assembly=mscorlib"

Edit: Workaround: As Steven mentioned, adding the resource through code-behind seems to work fine:

Resources.Add("ADecimalValue", new Decimal(1000.0));

Edit: Answer: Doing exactly the same thing in WPF seems to work fine. So I guess this is a hidden silverlight restriction. Thanks to Steven for this finding.

like image 798
alf Avatar asked Aug 16 '11 15:08

alf


1 Answers

I have confirmed your finding that the Decimal type does not appear to work as a static resource in a UserControl's resources section. I do however see a couple workarounds that have been discussed here on StackOverflow, and that i have just personally verified to work with the Decimal type in Silverlight: Access codebehind variable in XAML

The workarounds include:

  • adding the resource from the code-behind (see the link above)
  • Referencing a property in the code behind using an "elementname" type binding
  • Accessing a public Decimal property on the user controls data context property.

The second workaround can be done like this:

<sdk:Label Name="label1" Content="{Binding ElementName=root, Path=DecimalProperty}" />

...where the root usercontrol tag is defined like this (this idea is from the link above also):

<UserControl x:Class="SilverlightDecimal.MainPage" x:Name="root" .... >

and this is in your user control's code-behind:

public decimal DecimalProperty
{
    get
    {
        ...
    }
    set
    {
         ...
    }
}
like image 165
Steven Magana-Zook Avatar answered Nov 09 '22 08:11

Steven Magana-Zook