Page 1 of 1

Static properties not initialized on LoadComponent()?

Posted: 08 Apr 2017, 05:38
by nokola
I have the following XAML (simplified and emphasied for readability):

XAML:
<UserControl x:Class="FantasiaPhone.BrushAndColorControl"
...
xmlns:t="clr-namespace:Translation">

...
<TextBlock Text="all colors" FontSize="14" VerticalAlignment="Bottom" HorizontalAlignment="Center" TextWrapping="Wrap" TextAlignment="Center"
t:Translate.Text="allColors" />
...
</UserControl>

That I load like so:
Load code:
NoesisXaml xaml = (NoesisXaml)UnityEngine.Resources.Load(Path.GetFileNameWithoutExtension(xamlPath));
xaml.LoadComponent(o);
Debug.Log("Loaded");

I also have the Translate class:
C# t:Translate code:
public class Translate : DependencyObject {
...
public static DependencyProperty TextProperty = DependencyProperty.RegisterAttached(
"Text", typeof(string), typeof(Translate), new PropertyMetadata(string.Empty, new PropertyChangedCallback(OnTextChanged)));
static void OnTextChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
{
Debug.Log("TEXT CHANGED");
}
...

I can load the XAML fine, display it fine, and OnTextChanged is called OK. However, I expect to see that the text changed event is called before "loaded":
Expected debug log:
TEXT CHANGED
Loaded

Actual debug log:
Loaded
TEXT CHANGED

After I call LoadComponent() I immediately go through the list of controls and update their text with translation. Since this is already in place I don't want to use bindings (they are also slower.)

Why is the above order of operations happening? How can I reliably determine that all controls have their t:Translate="..." handlers executed?

Re: Static properties not initialized on LoadComponent()?

Posted: 08 Apr 2017, 10:57
by ai_enabled
If I understood you correctly, the issue is that the attached property binding happens with some delay and you expect it to happen right after xaml.LoadComponent(o).
As a workaround you could try calling UpdateLayout() method for the loaded control right after xaml.LoadComponent(o).

Re: Static properties not initialized on LoadComponent()?

Posted: 08 Apr 2017, 22:05
by nokola
Thanks! Figured it out. UpdateLayout() doesn't trigger as well.
The XAML component has to be assigned to the visual tree, otherwise it will not trigger the static property handlers. I changed my translation code to refresh after adding the control to the visual tree and all is well now :)

Re: Static properties not initialized on LoadComponent()?

Posted: 11 Apr 2017, 16:36
by sfernandez
UI elements are not loaded until they are attached to the View as you discovered.
This is when you will start getting notification of property changes.