Search code examples
c#wpfxamlbindingcode-behind

Binding via XAML or Code behind


I'm creating a WPF application and at the top of the page I need to display a postal address. Underneath the postal address will be product information. The product information is returned from a datasource and bound to the datacontext. eg this.DataContext = myComplexType;

Staff need to manually switch which postal address is to be displayed. I think the best way would be to select would be via a radio button control. In other words, on my Page, I would have 3 radio buttons, *UK Address *USA Address *China Address and depending on which was selected, the appropriate text would be entered in the Textblock Name="txbPostalAddress" at the top of the page.

The postal addresses live within a class called Addresses (as strings). e.g. Code:

namespace DAL
{
    public class Addresses
    {
        public string GctHkAddress { get { return gctHkAddress;} }
        public string GctUsaAddress { get { return gctUsaAddress; } }
        public string GctUkAddress { get{return gctUkAddress;} }

        private string gctHkAddress = "Company Name\n Hong Kong \n";
        private string gctUsaAddress = "Company Name\n USA \n";
        private string gctUkAddress = "Company Name\n UK \n";
    }
}

My question is, should the binding be done in XAML or in code behind. I can do it in code behind quite easily but I get the feeling this negates the power of XAML. Does any one have any idea which is the better approach and if via XAML, any idea how or links to tutorials etc?

Thanks

Dave


Solution

  • If your question is where to set DataContext, it just depends sometimes, otherwise it does not matter.

    Usually ViewModel ( in short a class that has data, and commands), is set to DataContext.

    It can be done in following ways

    1. In XAML -> Create staticresource for ViewModel in XAML, and set using StaticResoure. Issue -> View has to know about ViewModel, ViewModel must have parameterless constructor

    2. In ViewModel -> Pass view to constructor of View Model, and set view.DataContext=this in ViewModel ctor Issue -> ViewModel has to know about View

    3. Attach outside View and ViewModel, this is usually done in custom bootstrap class (or by overriding App-> OnStartUp. Here View is instanciated, ViewModel is instanciated, View.DataContext is set to ViewModel Issue -> Custom initialization is required

    4. ViewModelLocator -> create ViewModelLocator instance in XAML as StaticResource, bind DataContext to Property of ViewModelLocator Advantage -> view, viewmodel remain loosely coupled.