【问题标题】:RelativeSource Binding Tooltip to UserControl DependencyProperty Error到 UserControl DependencyProperty 错误的 RelativeSource 绑定工具提示
【发布时间】:2011-09-01 07:40:04
【问题描述】:

我有一个自定义用户控件,它在 DispatcherTimer 滴答声上做一些动画,并更新该用户控件的 DependencyProperty:

public partial class EggCounter : UserControl
{
  DispatcherTimer eggTimer;

  public EggCounter()
  {
     // Required to initialize variables
     InitializeComponent();

     eggTimer = new DispatcherTimer();
     eggTimer.Interval = TimeSpan.FromSeconds(5);
     eggTimer.Tick += new EventHandler(eggTimer_Tick);
     eggTimer.Start();

     Eggs = 0;
  }

  void eggTimer_Tick(object sender, EventArgs e)
  {
     Eggs += 4;
     Pop.Begin();
     mePop.Play();
  }

  private void mePop_MediaEnded(object sender, RoutedEventArgs e)
  {
     mePop.Position = TimeSpan.FromSeconds(0);
  }

  /// <summary>
  /// The <see cref="Eggs" /> dependency property's name.
  /// </summary>
  public const string EggsPropertyName = "Eggs";
  /// <summary>
  /// Gets or sets the value of the <see cref="Eggs" />
  /// property. This is a dependency property.
  /// </summary>
  public int Eggs
  {
     get
     {
        return (int)GetValue(EggsProperty);
     }
     set
     {
        SetValue(EggsProperty, value);
     }
  }
  /// <summary>
  /// Identifies the <see cref="Eggs" /> dependency property.
  /// </summary>
  public static readonly DependencyProperty EggsProperty = DependencyProperty.Register(EggsPropertyName, typeof(int), typeof(EggCounter), new UIPropertyMetadata(0));
}

此代码的 XAML 无关紧要。然后,我将此控件放在我的 MainPage 上,如下所示:

<my:EggCounter ToolTipService.ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=Eggs, StringFormat='{} Our chickens have laid {0} eggs since you have been here.'}"/>

页面加载正常,但是一旦计时器触发,我就会收到此错误:

"The given key was not present in the dictionary."

在我的用户控件中 Eggs 属性的设置器中,即在这一行:

SetValue(EggsProperty, value);

我也在控件上尝试了 ElementBinding,但得到了同样的错误。我对依赖属性做错了吗?

【问题讨论】:

  • 您的代码包含UIPropertyMetaData。 Silverlight 没有此类,您确定要使用 Silverlight 标记还是应该使用 WPF 标记?
  • 就是这样。使用了 WPF DP 代码 sn-p。将其更改为 PropertyMetaData 解决了该问题。如果你把它作为一个答案,你会得到战利品。

标签: silverlight xaml binding


【解决方案1】:

您的代码包含UIPropertyMetaData。 Silverlight 没有这个类,它只使用PropertyMetaData。

虽然说你描述的失败模式似乎表明你的代码可以编译,但我不明白是怎么走到这一步的。

【讨论】:

    【解决方案2】:

    如果使用您的代码,我不会收到错误消息。

    但我没有台词

    Pop.Begin();
    mePop.Play();
    

    在 TimerCallback 中。所以很可能你应该在这两种方法中寻找错误..

    【讨论】:

      猜你喜欢
      • 2012-06-06
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 2014-05-03
      • 2014-11-19
      相关资源
      最近更新 更多