Master Master - 4 months ago 13
C# Question

Creating Objects With Caliburn Events Behind Code

At the moment I create my object on the XAML side of the application. But I'm looking to create the objects programmatically to make the software more customizable and flexible.

XAML side

<Grid cal:Message.Attach="[MouseUp] = [AddBusiness]">
<Rectangle Fill="DarkOliveGreen"/>
<ContentControl ContentTemplate="{StaticResource Icons.BusinessCard}" Width="70"/>
<TextBlock Text="{Binding NewBusiness}" FontSize="14"/>
</Grid>


The problem I'm currently having is with attaching the Caliburn event to my Grid from code behind. How do I do that?

Answer

Given your code should look like

<Grid x:Name="MyGrid" cal:Message.Attach="[MouseUp] = [AddBusiness]">
    <Rectangle Fill="DarkOliveGreen"/>
    <ContentControl ContentTemplate="{StaticResource Icons.BusinessCard}" Width="70"/>
    <TextBlock Text="{Binding NewBusiness}" FontSize="14"/>
</Grid>

Here is the code representation of the Attach

var grid = MyGrid; // assuming this is code behind of above view
Message.SetAttach(grid, "[MouseUp] = [AddBusiness]");