I use MVVM. Is there any convenient way not to have xaml.cs files but somehow still calling InitializeComponent()?
views:
108answers:
1
+3
Q:
Wpf: Alternative to xaml.cs file containing only deafult constructor and InitializeComponent() call
+2
A:
Hi Naeron,
Check this out:
<Window x:Class="WpfApplication1.TestBrowser"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Initialize Component Test"
Height="300"
Width="300">
<StackPanel>
<ListBox x:Name="lb"/>
<x:Code>
<![CDATA[
public TestBrowser()
{
InitializeComponent();
lb.ItemsSource = new[] { "Hey" };
}
]]>
</x:Code>
</StackPanel>
</Window>
When such a XAML file is compiled, the contents inside the x:Code element get plopped inside the partial class in the .g.cs file.
I still would not recommend this practice. As for me it makes code less readable, and I'm not sure whether Blend or Kaxaml understands it.
Anvaka
2010-03-02 11:20:59
I like it but maybe something more declarative would be better. Perhaps a custom tag?
naeron84
2010-03-02 12:17:47
Really doubt it is possible. InitializeComponent() loads XAML, and only then it's processed. Alternatives may include loading XAML resources manually, somewhere in Application, but it's a headache.
Anvaka
2010-03-02 12:34:34
It contradicts the example above. Or you mean except <![CDATA[ .. ]]> ?
naeron84
2010-03-02 13:47:36
I would accept your answer if you could at least semi-proof that no better solution exists.
naeron84
2010-03-03 09:09:44
Naeron, the latest comment doesn't contradict the example. x:Code is processed by XAML compiler and it's not interpreted in runtime...
Anvaka
2010-03-03 12:46:53
Ok, I see now. I accept your solution.
naeron84
2010-03-03 14:19:43