views:

324

answers:

3

I am a bit surprised that while learning WPF/XAML/Silverlight almost all of the XAML/C# examples I have encountered have the "Click" events in the XAML and very few in the Window or Page constructor.

With all the emphasis these days on "non-intrusive Javascript", I would think that more developers would actually be structuring their XAML/code-behind like this:

XAML:

<Grid>
    <Button x:Name="btnEdit"/>
</Grid>

Code behind:

public Window1()
{
    InitializeComponent();

    btnEdit.Content = "Edit";
    btnEdit.Click += new RoutedEventHandler(btnEdit_Click);
}

private void btnEdit_Click(object sender, RoutedEventArgs e)
{
    btnEdit.Content = "This button was clicked.";
}

Any thoughts on why this would be a good or bad practice?

+1  A: 

If I remember correctly, I think that there is a partial class which implements the Init code above that is code gened by visual studio. I can’t speak for WPF, but it does this in ASP.Net 2.0, so I’m assuming that it does it the same here. It took me forever to get used to this.

I agree. I hate defining events in the markup.

Charles Graham
+3  A: 

Most of the smaller WPF examples give just an impression what is possible without focusing on design issues or good style.

In real world applications XAML should only be used for declarative programming. For example, binding a command to a button or declaring a data binding. Karl Shifflett has some great articles about the MVVM pattern which separates the concerns of your WPF/Silverlight application very well.

Code behind is in my opinion just suitable for tiny applications. It tends to mix view, control and data.

olli
A: 

I agree with your concern.

After much debate, we are following a similar pattern of non-intrusive, ultra-lean XAML and binding commands and data in code-behind.

If you add events in the XAML there is a contextual menu navigation to the event code. If you bind commands in XAML there is no equivalent. You can navigate from the command declaration in the XAML but not where it is assigned to the Command property on a control.

Andy Dent