我有一个自定义用户控件,做一个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的控件,但得到相同的错误。我做的依赖项属性有问题吗?
你的代码包含'UIPropertyMetaData'。 Silverlight没有这个类,你确定你打算使用Silverlight标签,还是应该使用WPF标签? – AnthonyWJones
就是这样。使用了WPF DP代码片段。将其更改为PropertyMetaData可解决问题。如果你将它作为答案,你会得到战利品。 – grimstoner