对 WPF 控件的类文件访问,如代码隐藏

本文关键字:代码 隐藏 访问 文件 WPF 控件 | 更新日期: 2023-09-27 18:35:14

我有三个文件,分别是myfile.xaml,myfile.xaml.cs还有一个类名:myclass.cs。

是否可以组合三个文件可以相互访问。

我想要

的是,我想要myclass.css可以像代码一样访问所有WPF控件(myfile.xaml.cs),我花了2天,但仍然没用,所以我真的需要有人回答我的问题,如果你知道这个问题。

请帮帮我!

对 WPF 控件的类文件访问,如代码隐藏

myclass.cs做什么?也许它根本不应该直接访问这些 WPF 控件。在其中实现一些事件,然后将窗口绑定到这些事件可能是一种更好、更干净、更易于维护的方法。

简单、可编译的示例:

MyClass.cs

namespace WpfApplication1
{
    // this class does not know anything about the window directly
    public class MyClass
    {
        public void DoSomething()
        {
            if (OnSendMessage != null) // is anybody listening?
            {
                OnSendMessage("I'm sending a message"); // i don't know and i don't care where it will go
            }
        }
        public event SendMessageDelegate OnSendMessage; // anyone can subscribe to this event
    }
    public delegate void SendMessageDelegate(string message); // what is the event handler method supposed to look like? 
    // it's supposed to return nothing (void) and to accept one string argument
}

Window1.xaml

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <TextBox Name="tbMessage" /> <!-- just a textbox -->
    </Grid>
</Window>

Window1.xaml.cs(代码隐藏文件)

using System.Windows;
namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            var myClass = new MyClass();
            myClass.OnSendMessage += new SendMessageDelegate(myClass_OnSendMessage); // subscribing to the event
            myClass.DoSomething(); // this will call the event handler and display the message in the textbox.
            // we subscribed to the event. MyClass doesn't need to know anything about the textbox.
        }
        // event handler
        void myClass_OnSendMessage(string message)
        {
            tbMessage.Text = message;
        }
    }
}