What is the advantage of setting DataContext in code instead of XAML?

后端 未结 7 1273
小鲜肉
小鲜肉 2020-12-09 10:54

There seem to be two main ways to define DataContext in WPF:

  • either in code like this:

App.xaml.cs (taken from the WPF MVVM Too

相关标签:
7条回答
  • 2020-12-09 11:37

    In my experience, it is best to design an interface layout against at least a sample of the data it will present. To do otherwise is to be blind to cheap insights and expensive oversights.

    0 讨论(0)
  • 2020-12-09 11:40

    Having it in codebehind makes it easy to inject the datacontext using unity.

    0 讨论(0)
  • 2020-12-09 11:41

    There could be a kind of solution to this, using the DataObjectProvider to mask the fact that the data is instantiated outside of XAML.

    It will state what the type of the DataContext is, which should be enough for Blend to pick up the properties.

    I have not tried this yet, so take it with a grain of salt, but it is certainly worth investigating.

    0 讨论(0)
  • 2020-12-09 11:45

    You can (maybe in 2009 you couldn't) get the best of both worlds by using the d:DataContext attribute. You don't need any of that ViewModelLocator craziness if you're not ready for that yet :-)

    First make sure that you have the following XML namespace defined in your root element:

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    

    Then you can add the following attribute to an element in your xaml:

    d:DataContext="{d:DesignInstance IsDesignTimeCreatable=True, Type=vm:CustomerInsightViewModel}"

    In your xaml codebehind :

        public CustomerInsightUserControl()
        {
            InitializeComponent();
    
            if (!DesignerProperties.IsInDesignTool)
            {
                DataContext = new CustomerInsightViewModel();
            }
        }
    

    Then in your ViewModel:

        public CustomerInsightViewModel()
        {
            if (IsInDesignMode)
            {
                // Create design time data
                Customer = new Customer() {
                    FirstName=... 
                }
            }
            else {
                // Create datacontext and load customers
            }
        }
    

    Don't miss the IsDesignTimeCreatable=True or else Blend won't instantiate your class

    0 讨论(0)
  • 2020-12-09 11:55

    See Rob's article about design time data in Blend: http://www.robfe.com/2009/08/design-time-data-in-expression-blend-3/

    0 讨论(0)
  • 2020-12-09 11:59

    I don't like the idea of having Expression Blend try to instantiate my data objects.

    I set the DataContext through code where I am able to use Dependency Injection to inject the proper objects, services, providers or what else I am using to find my code.

    0 讨论(0)
提交回复
热议问题