XAML: access to controls inside user control

前端 未结 3 797
有刺的猬
有刺的猬 2021-01-14 08:45

I have userControl like this:


    

        
3条回答
  •  生来不讨喜
    2021-01-14 09:31

    You can't do that directly. Here are two alternatives.

    Solution 1 : use a ViewModel

    Use a view model class to store the properties that you need to display in your custom control.

    class MyButtonViewModel
    {
        public string Text { get;set; }
    }
    

    MyButton.xaml:

    MainWindow.xaml

    
        
    
    
    
    

    This use the MVVM pattern. See WPF Apps With The Model-View-ViewModel Design Pattern, if you never used it.

    Solution 2 : use a CustomControl

    Replace your UserControl by a CustomControl. In that case Text can be a dependency property, so that you can write.

    
    

    This is much more complex. See How to Create a WPF Custom Control.

    Which to choose ?

    If you intend to use your control in several different projects, and you need to be able to change the skin of the control, choose the UserControl.

    Otherwise, go for the ViewModel and eventually apply the MVVM pattern in the remaining off your project.

提交回复
热议问题