how do I access a XAML object from a class other than main?

后端 未结 1 1532
执笔经年
执笔经年 2021-01-28 04:44

If I try \"var mainpage new Mainpage()\" I will run the mainpage constructor and then all the fields in the XAML object will return to null. How to I access XAML objects in sil

相关标签:
1条回答
  • 2021-01-28 05:38

    First, let me get this rant out of the way: what you propose is very bad design. It fits the definition of smelly code.

    If you insist on doing it this way, the "best" approach to take is to declare some public variables on your page that return the actual UI elements.

    <UserControl x:Class="MyNamespace.MyPage"  ...>
        <Grid>
            <TextBox x:Name="SomeTextBox" Width="100" />
        </Grid>
    </UserControl>
    
    
    public class MyPage
    {
        public TextBox MyTextBox
        {
            get { return SomeTextBox; }
        }
    }
    
    
    public class SomeOtherClass
    {
        private void SomeFunction()
        {
            var page = new MyPage();
            page.MyTextBox.Text = "some text";
        }
    }
    

    Of course the preferred method would be to use something like the MVVM pattern to implement binding from your window to its viewmodel, then you can just read the property values from the viewmodel, this way you avoid trying to touch any UI elements from a totally different class.

    Another way to do it (without going the full MVVM route) is to inject the necessary values into the constructor of the control/page that you are instantiating, and from there you can assign them to the appropriate UI element properties. This is still smelly, but better than directly accessing the UI elements from the outside.

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