Search code examples
xamlcode-behind

is "non-intrusive code-behind" a good or bad practice?


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?


Solution

  • 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.