我有三個文件myfile.xaml,myfile.xaml.cs和另一個類名:myclass.cs。類文件訪問WPF控件,如代碼behinde
是否有可能將三個文件組合成可以互相訪問。我想要的是myclass.css可以像代碼behinde(myfile.xaml.cs)一樣訪問所有的WPF控件,我花了2天,但仍然沒用,所以我真的需要有人回答我的問題,如果你知道這個問題。
請幫幫我!
我有三個文件myfile.xaml,myfile.xaml.cs和另一個類名:myclass.cs。類文件訪問WPF控件,如代碼behinde
是否有可能將三個文件組合成可以互相訪問。我想要的是myclass.css可以像代碼behinde(myfile.xaml.cs)一樣訪問所有的WPF控件,我花了2天,但仍然沒用,所以我真的需要有人回答我的問題,如果你知道這個問題。
請幫幫我!
這是什麼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;
}
}
}
myclass.css做如添加項目到myfile.xaml中的列表框控件其實,如果我寫入代碼behinde(myfile.xaml.cs)是好的,但我想要的是myclass.css可以訪問myfile.xaml所有事件, 示例:添加項目然後selectionChange selectedItem類似窗口窗體使用selectIndexChange。 – user1417068
它爲什麼這樣做? 「myclass」代表什麼?例如,用戶或產品列表?在這種情況下,這個類是一個「模型」,它不應該關心顯示數據。一個班級應該只有一個責任。成爲數據的容器是一項責任。顯示它是另一個。這就是所謂的分離問題。即使你剛剛開始學習 - 從一開始就學習它是正確的。稍後會更痛苦,相信我。 –
'示例:添加項目然後選擇更改時selectedItem像窗口窗體使用selectIndexChange.' - 難以理解的我,對不起 –
1.什麼你試圖完成那個嗎? 2.「訪問所有WPF控件」究竟意味着什麼? –
部分課程呢?把控制權交給? –
使用數據綁定,可能使用任何MVVM模式。如果沒有,你將完全脫離WPF理念(並且你將很難維護應用程序) –