0

I want to prevent the ViewModel from beeing created at Designtime.

So, the header looks like this:

<UserControl x:Class="app.reports.sta"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:vm="clr-namespace:viewmod.reports.sta;assembly=viewmodAss"
             xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
             mc:Ignorable="d"              
             d:DesignHeight="1000" d:DesignWidth="1200"
             d:DataContext="{d:DesignInstance Type=vm:staViewModel, IsDesignTimeCreatable=False}"             
             Language="de-DE">

The DataContext is set as shown below:

<UserControl.DataContext>
    <vm:staViewModel/>
</UserControl.DataContext>
<!--With this part active, the designer throws an error from the viewmodel constructor -->
<!--Without this part, the designer works, but when the app is run, not data is displayed (which is quite obivous) -->

How can I set the DataContext so that the ViewModel won't be created at DesignTime?

Mister 832
  • 1,177
  • 1
  • 15
  • 34
  • simple - don't use ``. it creates more problems than it is worth – ASh Apr 08 '20 at 10:11
  • but then no data is shown. What is the preferred way to set the `DataContext`? – Mister 832 Apr 08 '20 at 10:21
  • @Mister832: Try to detect whether you're in design mode and then return as suggested [here](https://stackoverflow.com/questions/425760/is-there-a-designmode-property-in-wpf). – mm8 Apr 08 '20 at 15:33
  • @Mister832 I created a sample with the UI code you gave, the data can be displayed successfully, can you give the some code of Viewmodel? – DasiyTian_1203 Apr 16 '20 at 01:50

1 Answers1

0

If you use MVVM, the DataContext should be set externally, i.e. you have a MainViewModel with some hierarchy and your control gets the DataContext through DataBinding. In App.xaml.cs (override OnStartup) you set the DataContext of your MainWindow to your MainViewModel and then show your MainWindow. Keep in mind to clear the StartupUri in your App.xaml.

tziemek
  • 61
  • 1
  • 5