0

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?

4

1 回答 1

1

这是可能的,但不是你想做的。我能想到的一种解决方案是这样的自定义 MarkupExtension:

[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;
    }
}

使用此扩展,您可以添加 int 资源或 int 值。这是如何使用它:

  • 在您的资源中:

    <local:IntCalculator x:Key="CalcVal">
        <local:IntCalculator.ResourceNames>
            <clr:String>Constant1</clr:String>
            <clr:String>Constant2</clr:String>
        </local:IntCalculator.ResourceNames>
    </local:IntCalculator>
    
  • 显示值:

    <Label Content="{StaticResource CalcVal}"/>
    
于 2013-09-12T11:39:41.807 回答