2010-04-18 69 views
6

XAML:AG_E_PARSER_BAD_PROPERTY_VALUE Silverlight中绑定页面标题

<navigation:Page ... Title="{Binding Name}"> 

C#

public TablePage() 
{ 
    this.DataContext = new Table() 
    { 
     Name = "Finding Table" 
    }; 
    InitializeComponent(); 
} 

在其中标题绑定发生点在获取一的InitializeComponent错误AG_E_PARSER_BAD_PROPERTY_VALUE。我试过添加静态文本,它工作正常。如果我在其他地方使用绑定,例如:

<TextBlock Text="{Binding Name}"/> 

这也行不通。

我猜这是抱怨,因为DataContext对象没有设置,但如果我在InitializeComponent之前放置一个断点,我可以确认它被填充并设置Name属性。

任何想法?

回答

8

您只能在DependencyProperty支持的属性上使用数据绑定。例如,如果您查看TextBlock的文档,您会发现Text属性与DependencyProperty类型的公共静态字段具有匹配的TextProperty

如果您查看Page的文档,您会发现没有定义TitleProperty,因此Title属性不是依赖项属性。

编辑

有没有办法 “越权” 这可是你可以创建一个附加属性: -

public static class Helper 
{ 
    #region public attached string Title 
    public static string GetTitle(Page element) 
    { 
     if (element == null) 
     { 
      throw new ArgumentNullException("element"); 
     } 
     return element.GetValue(TitleProperty) as string; 
    } 

    public static void SetTitle(Page element, string value) 
    { 
     if (element == null) 
     { 
      throw new ArgumentNullException("element"); 
     } 
     element.SetValue(TitleProperty, value); 
    } 

    public static readonly DependencyProperty TitleProperty = 
      DependencyProperty.RegisterAttached(
        "Title", 
        typeof(string), 
        typeof(Helper), 
        new PropertyMetadata(null, OnTitlePropertyChanged)); 

    private static void OnTitlePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     Page source = d as Page; 
     source.Title = e.NewValue as string; 
    } 
    #endregion public attached string Title 

} 

现在你的页面的XAML可能看起来有点像: -

<navigation:Page ... 
    xmlns:local="clr-namespace:SilverlightApplication1" 
    local:Helper.Title="{Binding Name}"> 
+0

啊我明白了。我假设没有办法重写这个? – zXynK 2010-04-18 19:20:21

+0

@zXynK:附加属性可能适用于您的情况,编辑答案以显示如何完成。 – AnthonyWJones 2010-04-18 20:07:26

+0

感谢您的帮助。 – zXynK 2010-04-19 20:19:43

0

将以下内容添加到MyPage.xaml.cs中:

public new string Title 
{ 
    get { return (string)GetValue(TitleProperty); } 
    set { SetValue(TitleProperty, value); } 
} 
public static readonly DependencyProperty TitleProperty = 
    DependencyProperty.Register("Title", 
     typeof(string), 
     typeof(Page), 
     new PropertyMetadata("")); 

一旦您将此属性(依赖项属性)添加到您的代码后面,您的代码将正常工作。