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

怎甘沉沦 提交于 2019-11-28 08:28:16
Simon_Weaver

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

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.

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

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.

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

It should also be possible to use ObjectDataProvider to establish an object factory using Unity or other IOCs as implied here...

http://social.msdn.microsoft.com/Forums/en/wpf/thread/1ff9e90e-302e-436e-bab3-ca4bad2b85af

in particular...

http://www.codeproject.com/Articles/43806/WPF-Ninject-Dojo-The-Data-Provider.aspx

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!