使用staticresource设置xaml中的结构值

时间:2017-01-04 22:40:07

标签: wpf xaml

例如:

xmlns:sys="clr-namespace:System;assembly=mscorlib"
<sys:String x:Key="Str1">Hello World</sys:String>
<sys:Int32 x:Key="Int1">1</sys:Int32>

现在可以用StaticResources替换内部部件,例如:

<sys:String x:Key="Str1">{StaticResource StrRes}</sys:String>
<sys:Int32 x:Key="Int1">{StaticResource IntRes}</sys:Int32>

1 个答案:

答案 0 :(得分:2)

不,我不这么认为。分配给XAML标记中定义的不可变结构的值必须是编译时常量。

但是为什么你还需要这个呢?以与现有资源完全相同的值定义另一个XAML资源的重点是什么?然后你也可以直接使用/引用原始资源。

也许您想要使用自己的自定义&#34;代理&#34;具有字符串属性的依赖项对象:

public class MyString : DependencyObject
{
    public static readonly DependencyProperty TheStringProperty =
         DependencyProperty.Register("TheString", typeof(string), typeof(MyString));

    public string TheString
    {
        get { return (string)GetValue(TheStringProperty); }
        set { SetValue(TheStringProperty, value); }
    }
}
<sys:String x:Key="Str1">Hello World</sys:String>
<local:MyString x:Key="StrRes" TheString="{StaticResource Str1}" />
...
<TextBlock Text="{Binding TheString, Source={StaticResource StrRes}}" />