How to use d:DesignInstance with types that don't have default constructor?

前端 未结 3 1160
轮回少年
轮回少年 2020-12-13 14:03

I am binding a textbox to an object, like so:

  

        
相关标签:
3条回答
  • 2020-12-13 14:25

    The default constructor is required for a type to be instantiated in XAML. As a workaround you can simply create a subclass of TaskVM that will have the default contructor and use it as a design time data context.

    <TextBlock d:DataContext="{d:DesignInstance ViewModel:DesignTimeTaskVM }" 
               Text="{Binding Title}" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown">
    </TextBlock>
    

    Another alternative is to set d:IsDesignTimeCreatable to False and a substitute type will be created for you at runtime (using your TaskVM type as a "shape").

    <TextBlock d:DataContext="{d:DesignInstance ViewModel:DesignTimeTaskVM, IsDesignTimeCreatable=False}" 
               Text="{Binding Title}" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown">
    </TextBlock>
    
    0 讨论(0)
  • 2020-12-13 14:33

    Another alternative would be to use a static class to hold the view model and call that class from the XAML. Here is an example:

    The xaml uses a view model factory to create the design data context:

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d"
    d:DataContext="{x:Static local:ViewModelFactory.ViewModel}"
    


    The static ViewModelFactory constructs the view model in its constructor and stores it in a public property where it can be accessed from outside (from the XAML):

    public static class ViewModelFactory
    {
        /// <summary>
        /// Static constructor.
        /// </summary>
        static ViewModelFactory()
        {
            ViewModel = new TypeOfViewModel(null);
    
            // further configuration of ViewModel
        }
    
        public static TypeOfViewModel ViewModel
        {
            get; set;
        }
    }
    



    Please note that the TypeOfViewModel class has no parameterless constructor. So the ViewModelFactory has to pass some value, in this case null.

    So in this scenario the TypeOfViewModel class would need to be implemented in a way that it is aware that during design time the passed in dependency is null.

    public class TypeOfViewModel
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="dependency">May be null at design time</param>
        public TypeOfViewModel(SomeDependentClass dependency)
        {
    
        }
    }
    
    0 讨论(0)
  • 2020-12-13 14:44

    You could add a default constructor to your VM. It could then check if it is in design time and set appropriate design-time values for its properties.

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