I have a button that loads XAML from a file, creates a control from it and adds this control as a child to a canvas that is part of a template present in the resources of a dockpanel on the window. The window also has a combobox named cboTColour and a combobox named cboBColour which I use to set a simple gradient background on my loaded control.
I load the XAML and add it to my canvas using the following code:
XmlReader xaml = XmlReader.Create(filename);
newControl = (Viewbox)XamlReader.Load(xaml);
((Canvas)(testButton.Template.FindName("MyCanvas", testButton))).Children.Clear();
((Canvas)(testButton.Template.FindName("MyCanvas", testButton))).Children.Add(newControl);
And here is the XAML I load:
<?xml version="1.0" encoding="utf-8"?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="Document" Stretch="Fill">
<Canvas Height="64" Width="128" ClipToBounds="True">
<Canvas.Background>
<!--Horizontal Gradient-->
<LinearGradientBrush StartPoint="1,0">
<GradientStop Color="{Binding ElementName=cboTColour, Path=SelectedItem.Name}" Offset="0"></GradientStop>
<GradientStop Color="{Binding ElementName=cboBColour, Path=SelectedItem.Name}" Offset="1"></GradientStop>
</LinearGradientBrush>
</Canvas.Background>
</Canvas>
</Viewbox>
I have tried putting the XAML straight into the designer and it works perfectly so it is not an issue with that. When I load the XAML from file, the controls are being created and placed correctly, but the databinding does not work - the colours do not change. I get the following errors:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=cboTColour'. BindingExpression:Path=SelectedItem.Name; DataItem=null; target element is 'GradientStop' (HashCode=24393646); target property is 'Color' (type 'Color')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=cboBColour'. BindingExpression:Path=SelectedItem.Name; DataItem=null; target element is 'GradientStop' (HashCode=23972246); target property is 'Color' (type 'Color')
I assume what's happening is when the XAMLReader loads the xaml ad creates a control from it, it is not sure of the path to my combo-boxes, as the xaml is not yet part of the window, and when the control is added to the window, this binding doesn't update, but I do not know how to either modify my bindings in the XAML to reflect where my combo-boxes would be situated in relation to it or to modify the XAMLReader or overall datacontext to take into account my controls. I can also assure you that the comboboxes have been created by this point as the code runs when a button is pressed on the window the comboboxes are in.
I MUST specify that I CANNOT modify the bindings themselves in the code, as the bindings will appear in various places and at various times throughout the different XAML files I will load.
Any help would be much appreciated.