我有一个自定义usercontrol,它在DispatcherTimer滴答上做一个小动画,以及更新usercontrol的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,但得到相同的错误。我做了什么错误的依赖属性?
您的代码中包含UIPropertyMetaData
。Silverlight没有这个类,它只使用PropertyMetaData
代替。
我已经说过你描述的失败模式似乎表明你的代码可以编译,我不明白是怎么做到的。
如果使用您的代码,我不会得到错误。
但是我没有
Pop.Begin();
mePop.Play();
在TimerCallback中。所以也许你应该在这两个方法中寻找错误。