tags:

views:

108

answers:

1

I use MVVM. Is there any convenient way not to have xaml.cs files but somehow still calling InitializeComponent()?

+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
I like it but maybe something more declarative would be better. Perhaps a custom tag?
naeron84
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
It contradicts the example above. Or you mean except <![CDATA[ .. ]]> ?
naeron84
I would accept your answer if you could at least semi-proof that no better solution exists.
naeron84
Naeron, the latest comment doesn't contradict the example. x:Code is processed by XAML compiler and it's not interpreted in runtime...
Anvaka
Ok, I see now. I accept your solution.
naeron84