This project has moved. For the latest updates, please go here.

A null refrence error when use DataTemplate.

Apr 19, 2012 at 4:15 PM

Hi,

I Use a DataTemple for wire View up to ViewModel. But the ViewModel.Value is null when I the following code:

 

 [Export(typeof(IRichTextView1)), PartCreationPolicy(CreationPolicy.NonShared)]
    public partial class RichTextView1 : UserControl, IRichTextView1
    {
        private readonly Lazy viewModel;
        private bool suppressTextChanged;
        private IEnumerable dynamicContextMenuItems;


        public RichTextView1()
        {
            InitializeComponent();

            viewModel = new Lazy(() => ViewHelper.GetViewModel(this));
            Loaded += FirstTimeLoadedHandler;
            IsVisibleChanged += IsVisibleChangedHandler;
        }


        private RichTextViewModel1 ViewModel
        {
            get
            {
                return viewModel.Value;
            }
        }


        private void FirstTimeLoadedHandler(object sender, RoutedEventArgs e)
        {
            // Ensure that this handler is called only once.
            Loaded -= FirstTimeLoadedHandler;

            suppressTextChanged = true;
            //    richTextBox.Document = ViewModel.Document.Content;
            suppressTextChanged = false;
        }

        private void IsVisibleChangedHandler(object sender, DependencyPropertyChangedEventArgs e)
        {
             ViewModel.IsVisible = IsVisible;
        }

Thanks for your helps.
Asad

 

 

Coordinator
Apr 21, 2012 at 8:30 PM

When I started with the ViewModel Pattern I have investigated the DataTemplate mechanism first. Unfortunately, it doesn’t come with the necessary flexibility I need for ViewModels (Controlling the lifecycle, injection of dependent objects). That is the reason why WAF is using the Dependency Injection and Service Locator pattern for creating the Views and ViewModels.

A WAF ViewModel cannot be created by the DataTemplate mechanism because the constructor needs the View object (which is decoupled from the concrete View implementation via the IView interface).

WAF supports another pattern: DataModel-View-ViewModel Pattern.  Please use DataModels instead of ViewModels when the DataTemplate mechanism should be responsible for the object creation.