我有三个文件myfile.xaml,myfile.xaml.cs和另一个类名:myclass.cs。
是否可以合并三个文件可以互相访问。
我想要的是,我希望myclass.css可以像代码behinde(myfile.xaml.cs)一样访问所有WPF控件,我花了2天,但仍然没用,所以我真的需要有人回答我的问题,如果你知道这个问题。
请帮帮我!
答案 0 :(得分: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;
}
}
}