我在XAML中定义了两个常量,我想基于这两个定义第三个:
<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>
有可能吗?
答案 0 :(得分: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}"/>