Code-behind static/dynamic properties in WPF and Naming Conundrum
-
29-10-2019 - |
Question
I have a button defined in my XAML which has a button style and a vector graphic, it is defined thus:
<Button
Height="48"
Width="48"
mvp:Presenter.Action="CreateStudentApplication"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Grid.Row="5"
Grid.Column="3"
Style="{DynamicResource BaseButton2}">
<ContentControl Template="{StaticResource ApplicationVector}"/>
</Button>
In my code-behind, I have a method that dynamically adds new buttons similar to this one to a StackPanel. In brief, it does something to the tune of:
var button = new Button();
button.Height = 48;
button.Width = 48;
button.Tag = x.ID;
button.SetResourceReference(TemplateProperty, "ApplicationVector");
button.SetResourceReference(StyleProperty, "BaseButton2");
Now here's the weird part- It displays only the vector graphic, and no button behind it. When I remove the penultimate line (the line with the vector reference), it displays the button styled as it should be! I'm assuming that setting the template is overriding the style, however they seem to play amicably in XAML. I have also tried setting the ContentProperty instidead of TemplateProperty, but this resulted in a string of the type. Any ideas? Thank you!
Solution
Your XAML and code behind are not equivalent. In the XAML, you are setting the Content
property of the button to be a ContentControl
. In the code behind, you are setting the Template
(or Content
) property to be the ApplicationVector
resource.
You would need to set the Content
property of the button to be an instance of a ContentControl
whose Template
property is set to be your ApplicationVector
resource.
var contentControl = new ContentControl();
contentControl.SetResourceReference(TemplateProperty, "ApplicationVector");
button.Content = contentControl;