在XAML中使用在Silverlight中的代码中创建的静态对象

时间:2009-03-12 19:33:48

标签: c# .net wpf silverlight xaml

我无法在Silverlight中使用它,因此我创建了两个测试项目。一个简单的WPF项目和一个简单的Silverlight项目,它们只做一件事:在代码中设置一个公共静态只读变量,并在一个完全裸的XAML中使用它。在WPF中,工作顺利。在Silverlight中,我收到以下编译器警告和运行时错误:

警告2 XML命名空间“http://schemas.microsoft.com/winfx/2006/xaml”中不存在“静态”标记...

属性Text的属性值{x:Static SilverlightApplication3:Page.Test}无效。 [线:7位置:25]

我认为Silverlight 2不支持这个,或者我只是遗漏了一些非常简单的东西?这是两者的完整代码,以防它是后者:

public partial class Window1 : Window
{
    public static readonly string Test = "test";
    public Window1()
    {
        InitializeComponent();
    }
}

<Window x:Class="WpfApplication4.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
        xmlns:WpfApplication4="clr-namespace:WpfApplication4">    
    <Grid>
        <TextBlock Text="{x:Static WpfApplication4:Window1.Test}" />
    </Grid>
</Window>

这是SL版本:

public partial class Page : UserControl
    {
        public static readonly string Test = "test";
        public Page()
        {
            InitializeComponent();
        }
    }

<UserControl x:Class="SilverlightApplication3.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:SilverlightApplication3="clr-namespace:SilverlightApplication3"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock Text="{x:Static SilverlightApplication3:Page.Test}" />
    </Grid>
</UserControl>

5 个答案:

答案 0 :(得分:6)

不幸的是,Silverlight在功能方面有很多限制,你刚刚找到其中一个。 SL2不支持StaticMarkupExpression。你也不能自己定义它。

e.g。来自ms的人:http://blogs.msdn.com/edmaia/archive/2008/11/23/animating-objects-visibility-in-silverlight.aspx

诀窍可能是使用像

这样的对象
class Helper{
    public string Value {get{return Page.Test;}} 

// implement INotifyPropertyChange if you want updates
}

然后

<Grid.Resources>
     <somexmlns:Helper x:Key="Helper"/>
</Grid.Resources>

<TextBlock Text="{Binding Value, Source={StaticResource Helper}}"/>

答案 1 :(得分:5)

不幸的是,看起来Silverlight不支持绑定到静态属性:What is the {x:Static sdfsdf} equivalent?

答案 2 :(得分:3)

只要该类不是静态类,您就可以实际绑定到静态属性。所以使用前面的Helper类示例:

public class Helper
{
    public static string Value{ get {return Page.Test;} }
}

XAML将保持不变。

答案 3 :(得分:1)

我刚注意到你有一个关于绑定到颜色的次要问题。我不认为它可以在Silverlight中完成。我很确定Silverlight中绑定目标的最低要求是FrameworkElement。

答案 4 :(得分:-2)

静态对象只会被实例化一次,并且会持续到程序结束。静态对象即使不在范围内也可以保留其状态,但只能在其本地范围内可见。