【问题标题】:ag_e_parser_bad_property_value Silverlight Binding Page Titleag_e_parser_bad_property_value Silverlight 绑定页面标题
【发布时间】:2010-04-18 16:19:19
【问题描述】:

XAML:

<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 属性已设置。

有什么想法吗?

【问题讨论】:

    标签: silverlight silverlight-3.0


    【解决方案1】:

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

    如果您查看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}">
    

    【讨论】:

    • 啊,我明白了。我认为没有办法覆盖它?
    • @zXynK:附加属性可能适用于您的情况,请编辑答案以显示如何完成。
    • Title 不是 DependencyProperty 真的很愚蠢。但这是一个很好的解决方案。谢谢。
    • @Ken:我同意这是一个令人震惊的疏忽。
    【解决方案2】:

    将以下内容添加到 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(""));
    

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

    【讨论】:

      猜你喜欢
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 2023-03-07
      • 2011-07-20
      相关资源
      最近更新 更多