Franki1986
Franki1986

Reputation: 1436

Is it really possible to separate xaml and code behind?

I am new in wpf and there is something that I don't understand.. Everywhere I am reading about separation of code and UI. So how should it work, even if I can design everything in blend, my code behind has always to react on changes and change visibilities in other situations... So first thing without the names of the controls, the code behind won't compile... And even if I have the names, isn't it far impossible to coordinate this?

Upvotes: 0

Views: 631

Answers (3)

PiotrWolkowski
PiotrWolkowski

Reputation: 8782

What you've described is a typical approach for WinForms where achieving a real separation of UI and logic is not possible as the application is driven by events hooked to specific controls.

However, in WPF you do not use (or don't have to use) events for the communication between UI and the application logic. Main areas worth investigating for you are:

Very broad overview is that the XAML describes the layout and specifies where the layout should get data from. Proper data are present in the data context and the WPF engine is responsible for all the wiring (or the binding).

<TextBlock Text="{Binding Caption}" />

For instance in the code above the Text in the TextBlock will be populated with the value stored in the Caption property in the data context. (Usually the data context is specified on the level of a user control or user window.) In the code behind there is nothing that is related to the TextBlock or to populating it with the values.

What you will find in the code behind usually is only initialization of the DataContext:

public partial class MyUiClass
{
    public MyUiClass()
    {
        this.Loaded += (sender, e) => { this.DataContext = new MyViewModelClass(); }
    }
}

All the data are stored in the class set as a data context (MyViewModelClass in the example above).

As a next step I would recommend to go through some MVVM tutorials (there is quite a few good ones on YouTube).

Upvotes: 2

David L
David L

Reputation: 33823

In the context of the "separation of code and UI" discussion, you aren't separating the Xaml from the Code-Behind. Rather, you are separating the logic from the Xaml and, as a result, separating the logic from the Code-Behind as well.

When a Xaml control is constructed, not only is the xaml "view" constructed but so also is the backing partial class that initializes the control. As a result, you always have a code-behind. It's a fundamental part of how Xaml works.

Upvotes: 2

Tigran
Tigran

Reputation: 62246

There is something wrong in architecture you're talking about. You don't need names of control in the model data. The only thing model data interacts with are events/commands. In that way you have a separation between presentation and data where the model view is a bridge between those two.

Upvotes: 1

Related Questions