my problem is that the embedded dlls of MahApps.Metro and MahApps.Metro.IconPacks are not working fine.
Used the Visual Studio debugger to check if they are getting loaded and it worked fine. If it could not load them the program would throw a xaml exception.
But for some reason the ResourceDictionaries which are merged are not working in runtime.
Should look like this
But looks like this
(As you can see the text color is different and it is missing the icon on the right side => does not load the styles.)
It looks like the first picture if both Dll's are provided in the directory of the program.
My App.xaml
<Application x:Class="Launcher.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converter="clr-namespace:Launcher.Class.Converter"
>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/FlatSlider.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro.IconPacks;component/Themes/IconPacks.xaml" />
<ResourceDictionary Source="Controls\ColorBrushes.xaml"/>
<ResourceDictionary Source="Controls\CustomMetroWindow.xaml"/>
<ResourceDictionary Source="Controls\CustomListView.xaml"/>
<ResourceDictionary Source="Controls\NewsStyle.xaml"/>
<ResourceDictionary Source="Controls\TextImageBox.xaml"/>
<ResourceDictionary Source="Controls\GlowMetroButton.xaml"/>
<ResourceDictionary Source="Controls\ToggleSwitchWin10.xaml"/>
<ResourceDictionary Source="Simple Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
<converter:InverseBooleanConverter x:Key="InverseBooleanConverter" />
<converter:BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter" />
<converter:BooleanToVisibilityCollapsedConverter x:Key="BoolToVisibilityCollapsedConverter" />
<converter:MultiObjectToBooleanConverter x:Key="MultiObjectToBooleanConverter" />
<converter:DownloadProgressToVisibilityConverter x:Key="DownloadProgressToVisibilityConverter" />
<converter:MultiObjectToStatusBarColorConverter x:Key="MultiObjectToStatusBarColorConverter" />
<converter:MultiBooleanConverter x:Key="MultiBooleanConverter" />
<converter:MultiBooleanToVisibilityConverter x:Key="MultiBooleanToVisibilityConverter" />
<converter:OpacityToBooleanConverter x:Key="OpacityToBooleanConverter" />
</ResourceDictionary>
</Application.Resources>
My Program.cs
[STAThread]
public static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
var resourceName = Assembly.GetExecutingAssembly().GetName().Name + ".Dll." + new AssemblyName(args.Name).Name + ".dll";
if (!resourceName.Contains("resources"))
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
if (stream != null)
{
var assemblyData = new Byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
}
else
{
Assembly requestedAssembly = args.RequestingAssembly;
AssemblyName requestedAssemblyName = new AssemblyName(args.Name);
while (true)
{
// requesting name in format: %assemblyname%.resources
// rewrite to: %assemblyName%.%assemblyName%.%culture%.resources.dll
//
var baseName = requestedAssemblyName.Name.Substring(0, requestedAssemblyName.Name.Length - ".resources".Length);
var name = string.Format("{0}.Dll.Lang.{1}.{2}.resources.dll", baseName, requestedAssemblyName.CultureInfo.Name, Assembly.GetExecutingAssembly().GetName().Name);
// by default for resources the requestingAssembly will be null
Assembly asm = null;
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
// resources have the same name as their belonging assembly, so find by name
var parentName = requestedAssemblyName.Name.Substring(0, requestedAssemblyName.Name.Length - ".resources".Length);
// I'd love to use linq here, but Cecil starts fucking up when I do (null reference exception on assembly.Write)
// without a Linq query it works fine, though
// ReSharper disable once LoopCanBeConvertedToQuery
foreach (var assembly in assemblies)
{
if (assembly.GetName().Name == parentName)
{
asm = assembly;
}
}
if (asm == null)
{
// cannot find assembly from which to load
return null;
}
using (var stream = asm.GetManifestResourceStream(name))
{
if (stream != null)
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
return Assembly.Load(bytes);
}
}
// did not find the specific resource yet
// attempt to use the parent culture, this follows the .Net resource fallback system
// e.g. if sub resource de-DE is not found, then .Parent will be "de", if that is not found parent will probably be default resource
var fallback = requestedAssemblyName.CultureInfo.Parent.Name;
if (string.IsNullOrEmpty(fallback))
{
// is empty if no longer a parent
// return null so .Net can load the default resource
return null;
}
var alteredAssemblyName = requestedAssemblyName.FullName;
alteredAssemblyName = alteredAssemblyName.Replace(string.Format("Culture={0}", requestedAssemblyName.CultureInfo.Name), string.Format("Culture={0}", fallback));
requestedAssemblyName = new AssemblyName(alteredAssemblyName);
}
}
return null;
};
App.Main();
}
The control
<TextBox x:Name="Username"
Controls:TextBoxHelper.Watermark="{lex:Loc Key=LoginWindow.YourUsername}" Margin="0,20,0,9"
Text="{Binding Config.AuthUsername}"
IsEnabled="{Binding LoggingIn, Converter={StaticResource InverseBooleanConverter}}" TextAlignment="Justify"
>
<TextBox.Resources>
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource MetroTextImageBox}">
<Setter Property="Controls:TextBoxHelper.ButtonTemplate">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ButtonBase}">
<Grid Background="{TemplateBinding Background}">
<Rectangle>
<Rectangle.Fill>
<VisualBrush>
<VisualBrush.Visual>
<iconPacks:PackIconModern Kind="User" Foreground="{StaticResource MainIconBrush}" />
</VisualBrush.Visual>
</VisualBrush>
</Rectangle.Fill>
</Rectangle>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TextBox.Resources>
</TextBox>
This code works for me: (add all libraries as Embedded Resource and set startup object to this class)
public class Program
{
private static Assembly ExecutingAssembly = Assembly.GetExecutingAssembly();
private static string[] EmbeddedLibraries =
ExecutingAssembly.GetManifestResourceNames().Where(x => x.EndsWith(".dll")).ToArray();
[STAThreadAttribute]
public static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
App.Main();
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
// Get assembly name
var assemblyName = new AssemblyName(args.Name).Name + ".dll";
// Get resource name
var resourceName = EmbeddedLibraries.FirstOrDefault(x => x.EndsWith(assemblyName));
if (resourceName == null)
{
return null;
}
// Load assembly from resource
using (var stream = ExecutingAssembly.GetManifestResourceStream(resourceName))
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
return Assembly.Load(bytes);
}
}
}
The project file portion was cut off previous answer.
Add this to project file
<!--Then add this is project file.-->
<Target Name="EmbedReferencedAssemblies" AfterTargets="ResolveAssemblyReferences">
<ItemGroup>
<!-- get list of assemblies marked as CopyToLocal -->
<AssembliesToEmbed Include="#(ReferenceCopyLocalPaths)" Condition="'%(Extension)' == '.dll'" />
<!-- add these assemblies to the list of embedded resources -->
<EmbeddedResource Include="#(AssembliesToEmbed)">
<LogicalName>%(AssembliesToEmbed.DestinationSubDirectory)%(AssembliesToEmbed.Filename)%(AssembliesToEmbed.Extension)</LogicalName>
</EmbeddedResource>
</ItemGroup>
<Message Importance="high" Text="Embedding: #(AssembliesToEmbed->'%(DestinationSubDirectory)%(Filename)%(Extension)', ', ')" />
</Target>
<!-- no need to copy the assemblies locally anymore -->
<Target Name="_CopyFilesMarkedCopyLocal" />
I had the same issue you described and came across fix that resolves the issue.
public partial class App : Application {
public App() {
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
}
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args) {
var executingAssembly = Assembly.GetExecutingAssembly();
var assemblyName = new AssemblyName(args.Name);
var path = assemblyName.Name + ".dll";
if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false) {
path = String.Format(#"{0}\{1}", assemblyName.CultureInfo, path);
}
using (var stream = executingAssembly.GetManifestResourceStream(path)) {
if (stream == null)
return null;
var assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
return Assembly.Load(assemblyRawBytes);
}
}
}
%(AssembliesToEmbed.DestinationSubDirectory)%(AssembliesToEmbed.Filename)%(AssembliesToEmbed.Extension)
'%(DestinationSubDirectory)%(Filename)%(Extension)',
', ')" />
Related
As you can see in code below, I have descendant of ScrollViewer, and set Name of MyScrollView in ctor. But when I try using MyScrollViewer in control template I cannot find one via Template.FindName
If I change <local:MyScrollViewer /> to <local:MyScrollViewer Name=""PART_ContentHost"" /> code works as expected, but I am looking for solution without changing XAML.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var parserContext = new ParserContext
{
XamlTypeMapper = new XamlTypeMapper(new string[0]),
XmlnsDictionary =
{
{ "", "http://schemas.microsoft.com/winfx/2006/xaml/presentation" },
{ "x", "http://schemas.microsoft.com/winfx/2006/xaml" },
{ "local", "clr-namespace:" + typeof(MyScrollViewer).Namespace + ";assembly=" + typeof(MyScrollViewer).Assembly.FullName}
}
};
var template = (ControlTemplate)XamlReader.Parse(#"
<ControlTemplate TargetType=""TextBox"">
<Border>
<local:MyScrollViewer />
<!--<local:MyScrollViewer Name=""PART_ContentHost""/> -->
</Border>
</ControlTemplate>
", parserContext);
// Name=""PART_ContentHost""
Content = new MyTextBox { Template = template };
}
}
public class MyScrollViewer: ScrollViewer
{
public MyScrollViewer() => Name = "PART_ContentHost";
}
public class MyTextBox: TextBox
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var contentHost = Template.FindName("PART_ContentHost", this);
if (contentHost == null)
throw new Exception("Can not find PART_ContentHost");
}
}
updated:
Even I put my control template into MainWindow.xaml (and remove from MainWindow ctor), it doesnot work.
public MainWindow()
{
InitializeComponent();
}
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.Resources>
<ControlTemplate TargetType="local:MyTextBox" x:Key="TextBoxTemplate">
<local:MyScrollViewer />
</ControlTemplate>
</Grid.Resources>
<local:MyTextBox Template="{StaticResource TextBoxTemplate}" />
</Grid>
</Window>
The constructor of MyScrollViewer will not be called on template creation with XamlReader, so the names with which MyScrollViewer was created are stored in internal dictionaries. See template.ChildNames. The constructor of MyScrollViewer will first being called, when MyTextBox becomes visible, but it's already too late.
Template being created from XAML and it notices the children names by parsing, without creation of children instances. Later the children instances will be created, but the template hold old names. So if you call Template.FindNames with new names, they will not be found.
Try
var contentHost = Template.FindName("2_T", this);
but I am looking for solution without changing XAML
Setting the name in the constructor of the ScrollViewer won't work. You have to set it in the template for it to be registered in the namescope of the template.
If you don't want to assign the element a Name in the template, you could wait for it to get created and then find it in the visual tree without using a name:
public class MyTextBox : TextBox
{
public MyTextBox()
{
Loaded += MyTextBox_Loaded;
}
private void MyTextBox_Loaded(object sender, RoutedEventArgs e)
{
MyScrollViewer sv = FindVisualChild<MyScrollViewer>(this);
//...
}
private static T FindVisualChild<T>(Visual visual) where T : Visual
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
{
Visual child = (Visual)VisualTreeHelper.GetChild(visual, i);
if (child != null)
{
T correctlyTyped = child as T;
if (correctlyTyped != null)
{
return correctlyTyped;
}
T descendent = FindVisualChild<T>(child);
if (descendent != null)
{
return descendent;
}
}
}
return null;
}
}
I want to display a MetroDialog with a custom background color, for error messages.
I tried using the property CustomResourceDictionary without luck:
Function to display message:
public static async Task<MessageDialogResult> DialogOK(string title, string message)
{
MetroDialogSettings settings = new MetroDialogSettings();
settings.CustomResourceDictionary = new ResourceDictionary { Source = new Uri("pack://application:,,,/MyApp;component/Resources/ErrorDialogRD.xaml") };
var result = await mainWindow.ShowMessageAsync(title, message, MessageDialogStyle.Affirmative, settings );
return result;
}
Resource dictionary:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Dialogs="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro">
<Style TargetType="{x:Type Dialogs:BaseMetroDialog}">
<Setter Property="Background" Value="Red" />
</Style>
</ResourceDictionary>
What am I missing? :)
How can i load style from below xaml using XamlReader.Load()
<Window
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
xmlns:dxgt="http://schemas.devexpress.com/winfx/2008/xaml/grid/themekeys"
>
<ResourceDictionary>
<Style x:Key="LastRowHighlighted"
BasedOn="{StaticResource {dxgt:GridRowThemeKey ResourceKey=RowStyle}}"
TargetType="{x:Type dxg:GridRowContent}">
</Style>
</ResourceDictionary>
Try something like this:
public void LoadStyle(string fileName)
{
if (File.Exists(fileName))
{
try
{
using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
ResourceDictionary resourceDictionary = (ResourceDictionary)XamlReader.
Load(fileStream);
Resources.MergedDictionaries.Clear(); // optional
Resources.MergedDictionaries.Add(resourceDictionary);
}
}
catch { }
}
}
I have a WPF application with a theme (ShinyRed.xaml) and I want to have a button that when clicked changes the theme to ShinyBlue.xaml
I load in the theme initially in App.xaml:
<Application.Resources>
<ResourceDictionary Source="/Themes/ShinyBlue.xaml"/>
</Application.Resources>
How might I do this?
How you could do it:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary x:Name="ThemeDictionary">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Themes/ShinyRed.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
<!-- ... -->
public partial class App : Application
{
public ResourceDictionary ThemeDictionary
{
// You could probably get it via its name with some query logic as well.
get { return Resources.MergedDictionaries[0]; }
}
public void ChangeTheme(Uri uri)
{
ThemeDictionary.MergedDictionaries.Clear();
ThemeDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = uri });
}
//...
}
In your change method:
var app = (App)Application.Current;
app.ChangeTheme(new Uri("New Uri here"));
Here is an article that will walk you through it:
http://svetoslavsavov.blogspot.com/2009/07/switching-wpf-interface-themes-at.html
Basically you need to remove the "old" theme from the resource dictionary and then merge in the new one. The above article shows you how to make this change very simple.
Im using the following command to set the theme at runtime:
Application.Current.Resources.Source = new Uri("/Themes/ShinyRed.xaml", UriKind.RelativeOrAbsolute);
App.xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/Font.xaml" />
<ResourceDictionary Source="Themes/Light.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
In your code:
> Application.Current.Resources.MergedDictionaries[1].Source = new Uri("Themes/Dark.xaml", UriKind.RelativeOrAbsolute);
you can check with this to be sure nothing grow
Application.Current.Resources.MergedDictionaries.Count.ToString();
H.B.'s answer did not run for me, I had to do this (works, tested):
Uri dictUri = new Uri(#"/Resources/Themes/MyTheme.xaml", UriKind.Relative);
ResourceDictionary resourceDict = Application.LoadComponent(dictUri) as ResourceDictionary;
Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(resourceDict);
To pretty it up:
// Place in App.xaml.cs
public void ChangeTheme(Uri uri)
{
ResourceDictionary resourceDict = Application.LoadComponent(uri) as ResourceDictionary;
Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(resourceDict);
}
// Example Usage (anywhere in app)
private void ThemeRed_Click(object sender, RoutedEventArgs e)
{
var app = App.Current as App;
app.ChangeTheme(new Uri(#"/Resources/Themes/RedTheme.xaml", UriKind.Relative));
}
I have a solution with 2 projects: Windows Phone App and a Windows Phone Class Library. The class library has a control called MessageBoxExtended which inherits from ContentControl. The project also has a Themes folder with a generic.xaml file. The file has the Build Action set to Page and it looks like this:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:KontactU.Common.WPControls;assembly=KontactU.Common.WPControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Style TargetType="local:MessageBoxExtended">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MessageBoxExtended">
<Grid x:Name="LayoutRoot">
<StackPanel>
<TextBlock x:Name="lblTitle" Text="Title Goes Here" Style="{StaticResource PhoneTextTitle3Style}"/>
<TextBlock x:Name="lblMessage" Text="Some long message here repeated over and over again. Some long message here repeated over and over again. " TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button x:Name="btnLeft" Content="Button1" Click="btnLeft_Click"></Button>
<Button x:Name="btnCenter" Content="Button2" Click="btnCenter_Click"></Button>
<Button x:Name="btnRight" Content="Button3" Click="btnRight_Click"></Button>
</StackPanel>
</StackPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The control code looks like this:
public class MessageBoxExtended : ContentControl
{
private TextBlock lblTitle;
private TextBlock lblMessage;
private Button btnLeft;
private Button btnCenter;
private Button btnRight;
private bool currentSystemTrayState;
internal Popup ChildWindowPopup
{
get;
private set;
}
private static PhoneApplicationFrame RootVisual
{
get
{
return Application.Current == null ? null : Application.Current.RootVisual as PhoneApplicationFrame;
}
}
public MessageBoxExtended()
: base()
{
DefaultStyleKey = typeof(MessageBoxExtended);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
lblTitle = this.GetTemplateChild("lblTitle") as TextBlock;
lblMessage = this.GetTemplateChild("lblMessage") as TextBlock;
btnLeft = this.GetTemplateChild("btnLeft") as Button;
btnCenter = this.GetTemplateChild("btnCenter") as Button;
btnRight = this.GetTemplateChild("btnRight") as Button;
InitializeMessageBoxExtended("Title", "Message", MessageBoxExtendedButtonType.Ok);
}
private void InitializeMessageBoxExtended(string title, string message, MessageBoxExtendedButtonType buttonType)
{
HideSystemTray();
lblTitle.Text = title;
lblMessage.Text = message;
switch (buttonType)
{
case MessageBoxExtendedButtonType.Ok:
btnLeft.Visibility = System.Windows.Visibility.Collapsed;
btnRight.Visibility = System.Windows.Visibility.Collapsed;
btnCenter.Content = "ok";
break;
case MessageBoxExtendedButtonType.OkCancel:
btnCenter.Visibility = System.Windows.Visibility.Collapsed;
btnLeft.Content = "ok";
btnRight.Content = "cancel";
break;
case MessageBoxExtendedButtonType.YesNo:
btnCenter.Visibility = System.Windows.Visibility.Collapsed;
btnLeft.Content = "yes";
btnRight.Content = "no";
break;
}
}
public void Show(string title, string message, MessageBoxExtendedButtonType buttonType)
{
if (ChildWindowPopup == null)
{
ChildWindowPopup = new Popup();
try
{
ChildWindowPopup.Child = this;
}
catch (ArgumentException)
{
throw new InvalidOperationException("The control is already shown.");
}
}
if (ChildWindowPopup != null && Application.Current.RootVisual != null)
{
// Configure accordingly to the type
InitializeMessageBoxExtended(title, message, buttonType);
// Show popup
ChildWindowPopup.IsOpen = true;
}
}
private void HideSystemTray()
{
// Capture current state of the system tray
this.currentSystemTrayState = SystemTray.IsVisible;
// Hide it
SystemTray.IsVisible = false;
}
}
The Windows Phone App references it and calls it in the code behind by instantiating it and calling the Show method:
MessageBoxExtended mbe = new MessageBoxExtended();
mbe.Show();
The problem is that the OnApplyTemplate is never called. I've tried commenting out all the lines in the generic.xaml, but I get the same result.
Any ideas?
Never mind, it was my mistake. I added
if (lblTitle == null)
return;
to the InitializeMessageBoxExtended() method and now it works. If you follow the logic the constructor is called before the OnApplyTemplate() which calls the InitializeMessageBoxExtended() and therefore the values are null. By adding the code above the control doesn't throw an exception, it continues and when the control is part of the VisualTree the OnApplyTemplate is called.
Hope this helps anyone out there.