我有一個自定義用戶控件,做一個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