How to access WPF MainWindow Controls from my own .cs file

后端 未结 7 1197
执笔经年
执笔经年 2021-01-31 18:28

I am a NOVICE and am very much struggling with what seems should be a very simple task. How do I modify a property of a MainWindow TextBlock, from ano

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 19:27

    You can simply achieve this using MVVM. You shouldn't directly access controls in View using its name from another class. You have to use binding properties.

    First of all, add a class. This will be your ViewModel. Add your properties to this class which will be binded to your input controls in your View.

    Student ViewModel

    public class Student
    {
        public string Name
        {
            get { return "Setting Text from My Program"; }
        }
    }
    

    App.Config

    Now you have add to this View Model as a resource in your App.Config file. First, add the name space reference to your app.config where your VM resides. [xmlns:local="clr-namespace:WpfApplication2]. Add your VM class as a resource by specifying your View Model class name (student).

    
        
        
            
        
    
    

    MainWindow.xaml

    Set the DataContext with the resource key added to App.config and set the binding to the property defined in the Student View Model.

    
        
        
            
        
    
    

提交回复
热议问题