如何从另一个类或窗口访问WPF中的控件

Aha*_*our 12 c# silverlight wpf

我想在WPF中的mainWindow中访问我的控件,如按钮或文本框,但我不能这样做.

在Windows窗体应用程序中它很容易,您可以将该控件的修饰符设置为True,并且您可以从该mainWindow的实例到达该控件,但在WPF中,我无法声明公共控件.我怎样才能做到这一点?

Aha*_*our 27

对于其他WPF窗口中的访问控制,您必须将该控件声明为public,WPF中控件的默认声明是公共的,您可以使用以下代码指定它:

<TextBox x:Name="textBox1" x:FieldModifier="public" />
Run Code Online (Sandbox Code Playgroud)

之后你可以搜索应用程序中的所有活动窗口来查找,而不是像这样的控件:

foreach (Window window in Application.Current.Windows)
{
    if (window.GetType() == typeof(Window1))
    {
       (window as Window1).textBox1.Text = "I changed it from another window";
    }
}
Run Code Online (Sandbox Code Playgroud)


eMi*_*eMi 6

不幸的是,WPF的基础是数据绑定.以任何其他方式这样做是"违背谷物",是不好的做法,并且编码和理解通常更复杂.

对于您手头的问题,如果您要在视图之间共享数据(即使它只是一个视图),请创建一个视图模型类,其中包含表示数据的属性,并从视图中绑定到属性.

在您的代码中,仅管理您的视图模型类,而不是通过其可视控件和可视组合触摸实际视图.


Raf*_*ura 5

我发现在 WPF 中,您必须将 Window 转换为 MainWindow。

看起来很复杂,其实很简单! 但是,可能不是最佳实践。

假设我们在 MainWindow 中有一个 Label1、一个 Button1,并且您有一个类来处理与称为 UI 的用户界面相关的任何事情。

我们可以有以下几点:

主窗口类:

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        UI ui = null;
        //Here, "null" prevents an automatic instantiation of the class,
        //which may raise a Stack Overflow Exception or not.
        //If you're creating controls such as TextBoxes, Labels, Buttons... 

        public MainWindow()
        {
            InitializeComponent(); //This starts all controls created with the XAML Designer.
            ui = new UI(); //Now we can safely create an instantiation of our UI class.
            ui.Start();
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

界面类:

namespace WpfApplication1
{    
public class UI
    {
        MainWindow Form = Application.Current.Windows[0] as MainWindow;
        //Bear in mind the array! Ensure it's the correct Window you're trying to catch.

        public void Start()
        {
            Form.Label1.Content = "Yay! You made it!";
            Form.Top = 0;
            Form.Button1.Width = 50;
            //Et voilá! You have now access to the MainWindow and all it's controls
            //from a separate class/file!
            CreateLabel(text, count); //Creating a control to be added to "Form".
        }

        private void CreateLabel(string Text, int Count)
        {
            Label aLabel = new Label();
            aLabel.Name = Text.Replace(" ", "") + "Label";
            aLabel.Content = Text + ": ";
            aLabel.HorizontalAlignment = HorizontalAlignment.Right;
            aLabel.VerticalAlignment = VerticalAlignment.Center;
            aLabel.Margin = new Thickness(0);
            aLabel.FontFamily = Form.DIN;
            aLabel.FontSize = 29.333;

            Grid.SetRow(aLabel, Count);
            Grid.SetColumn(aLabel, 0);
            Form.MainGrid.Children.Add(aLabel); //Haha! We're adding it to a Grid in "Form"!
        }


    }
}
Run Code Online (Sandbox Code Playgroud)