Ryszard Dżegan
Ryszard Dżegan

Reputation: 25434

Combined constants in WPF XAML

I have two constants defined in XAML and I would like to define the third based on that two:

<UserControl ... xmlns:clr="clr-namespace:System;assembly=mscorlib">
    <UserControl.Resources>
        <clr:Int32 x:Key="Constant1">1</clr:Int32>
        <clr:Int32 x:Key="Constant2">2</clr:Int32>

        <!-- Is it possible to achieve something like this? -->
        <clr:Int32 x:Key="Constant3">{StaticResource Constant1} + {StaticResource Constant2}</clr:Int32>
    </UserControl.Resources>
</UserControl>

Is it possible?

Upvotes: 0

Views: 698

Answers (1)

Florian Gl
Florian Gl

Reputation: 6014

It is possible, but not as you want to do it. One solution I can think of is a custom MarkupExtension like this:

[MarkupExtensionReturnType(typeof(int))]
public class IntCalculator:MarkupExtension
{
    public List<int> Values { get; set; }

    public List<string> ResourceNames { get; set; } 

    public IntCalculator()
    {
        Values = new List<int>();
        ResourceNames = new List<string>();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var root = (IRootObjectProvider)serviceProvider.GetService(typeof(IRootObjectProvider));
        var rootObject = root.RootObject as FrameworkElement;
        int calcVal = 0;
        if (rootObject != null)
        {
            foreach (var resourceName in ResourceNames)
            {
                var resource = rootObject.FindResource(resourceName);
                if (resource != null && resource is int)
                {
                    calcVal += System.Convert.ToInt32(resource);
                }
            }
        }


        foreach (var value in Values)
        {
            calcVal += value;
        }
        return calcVal;
    }
}

With this Extension you can add int resources or int values. This is how to use it:

  • in your resources:

    <local:IntCalculator x:Key="CalcVal">
        <local:IntCalculator.ResourceNames>
            <clr:String>Constant1</clr:String>
            <clr:String>Constant2</clr:String>
        </local:IntCalculator.ResourceNames>
    </local:IntCalculator>
    
  • to display the value:

    <Label Content="{StaticResource CalcVal}"/>
    

Upvotes: 1

Related Questions