Conditional Resources Creation WPF XAML Design / Run time

前端 未结 2 1527
长发绾君心
长发绾君心 2021-01-24 02:06

Following a first question on WPF Cascading Binding,

I remarked that I had more Resources than desired defined in both the MainWindow

2条回答
  •  天涯浪人
    2021-01-24 02:52

    I will finally try to answer my own question

    Result is as awaited no "duplicate resources" in the lower level ViewModel instances The result in snoop: Snoop view. Only the mainwindow viewmodel instance

    The XAML code

    
    
    
        
    
    
    
            
        
            
        
    
    
    

    Note the new line:

    d:DataContext="{d:DesignInstance {x:Type vm_nmspc:my_usercontrol_vm}, IsDesignTimeCreatable=True}"

    And there is absolutely no other modifications !!

    The trick is to use the IDE to support you ( if you are unaware of the syntax that will result in the XAML ).

    I will try to illustrate what I did.

    Choose your object, and in the format menu choose Set Design Time DataContext

    Set Design Time DataContext

    Then choose your DesignInstance ( here the ViewModel my_usercontrol_vm) and do not forget to tick IsDesignTimeCreatable

    enter image description here

    This created the magic line in the Ellipse declaration but I moved it on the top of the XAML.

    So this answered my question. It is possible with no deep knowledge on WPF/XAML to make all your subviews (controls) "rendered" without the additional cost of wasted resources of viewmodels

    To give echo to what Maximus gave in the first answer, I found also another post (will try to find it again and quote it in a next edit) using directly the function DesignerProperties.GetIsInDesignMode( )

    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
    
            InitializeComponent();
    
            if (  DesignerProperties.GetIsInDesignMode(this))
            {
                //Do what you want here for design time specific actions
            }
        }
    }
    

提交回复
热议问题