2011-09-01 64 views
1

我有一个自定义用户控件,做一个DispatcherTimer剔一个小动画,以及更新用户控件的一个DependencyProperty:的RelativeSource绑定工具提示用户控件的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." 

在鸡蛋属性的setter在我的用户控件,即在这一行:

SetValue(EggsProperty, value); 

我也尝试过一个ElementBinding的控件,但得到相同的错误。我做的依赖项属性有问题吗?

+1

你的代码包含'UIPropertyMetaData'。 Silverlight没有这个类,你确定你打算使用Silverlight标签,还是应该使用WPF标签? – AnthonyWJones

+0

就是这样。使用了WPF DP代码片段。将其更改为PropertyMetaData可解决问题。如果你将它作为答案,你会得到战利品。 – grimstoner

回答

2

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

说了这么多你描述的故障模式似乎表明,你的代码编译,我不明白怎么连得那么远。

0

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

但我没有过线

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

。所以propably你应该寻求的错误在这两种方法..