【发布时间】: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