我有一个自定义用户控件,它在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."
在我的usercontrol中的Eggs属性的setter中,即在这一行:
SetValue(EggsProperty, value);
我还在控件上尝试了一个ElementBinding,但是得到了同样的错误。我是否在依赖属性上做错了什么?
答案 0 :(得分:2)
您的代码包含UIPropertyMetaData
。 Silverlight没有这个仅使用PropertyMetaData
的类。
说过你描述的失败模式似乎表明你的代码编译了,我甚至不明白你是怎么做到的。
答案 1 :(得分:0)
如果使用您的代码,我不会收到错误。
但我没有线
Pop.Begin();
mePop.Play();
在TimerCallback中。所以你应该在这两种方法中寻找错误。