-2

我有三个文件,myfile.xaml、myfile.xaml.cs 和另一个类名:myclass.cs。

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

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

请帮帮我!

4

1 回答 1

0

这是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;
        }
    }
}
于 2012-05-25T10:34:45.170 回答