Reputation: 2337
I have a custom control that has a dependency property. When SetValue is called on the Dependency property, nothing happens unless SetValue is called after a UI event gets fired. Look at the example below to see what I mean.
public static readonly DependencyProperty ItemDictionaryProperty = DependencyProperty.Register("ItemDictionary", typeof(Dictionary<string, Control>), typeof(ListBoxEx),
new FrameworkPropertyMetadata(new Dictionary<string, Control>(), FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender, OnItemDictionaryPropertyChanged));
private Dictionary<string, Control> itemDictionary = new Dictionary<string, Control>();
private static void OnItemDictionaryPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var test = (ListBoxEx)d;
test.ItemDictionary = (Dictionary<string, object>)e.NewValue;
// test.GetBindingExpression(ItemDictionaryProperty).UpdateSource();
}
public override void EndInit()
{
itemDictionary.Clear();
foreach (var item in this.Items)
itemDictionary.Add((item as Control).Tag.ToString(), item as Control);
this.ItemDictionary = itemDictionary; // This doesn't
base.EndInit();
}
public Dictionary<string, Control> ItemDictionary
{
get { return (Dictionary<string, Control>)GetValue(ItemDictionaryProperty); }
set { SetValue(ItemDictionaryProperty, value); }
}
protected override void OnMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e)
{
itemDictionary.Clear();
foreach (var item in this.Items)
itemDictionary.Add((item as Control).Tag.ToString(), item as Control);
ItemDictionary = itemDictionary; // This works
base.OnMouseLeftButtonDown(e);
}
When ItemDictionary
is updated in EndInit
. The binding property doesn't get updated.
As soon as I call it in an event method, then all of a sudden my changes effect the source.
I did a little test to see if my bindings were being created being EndInit
but setting the property equal to null in my viewmodels' constructor. So even though the binding works and it invokes OnItemDictionaryPropertyChanged
. Nothing in the source changes.
What am I missing?
Upvotes: 1
Views: 58
Reputation: 145
My guess is it could be an application lifecycle problem. Perhaps EndInit() gets called before ItemDictionaryProperty
gets set up with your new Dictionary<string, Control>()
in the FrameworkPropertyMetaData
. EndInit() appears to be related to only the graphical part of the control. MSDN for ISupportInitialize.EndInit
Try using the Loaded
event. Info on MSDN
Upvotes: 1