[英]Sending custom event form one page to another
我正在用C#和Xaml制作一個UWP 桌面應用程序,它是學校項目的銀行應用程序,我正在努力解決付款歷史邏輯。
我希望用戶在Page1上的文本框中輸入一些價格,然后按下按鈕,然后應用程序將導航到主屏幕。 如果付款成功(這個邏輯已經在我的應用程序中,你不必關注它)在Page2中將創建文本塊(但用戶將無法看到它,除非他打開Page2 )
第 1 頁.xaml
<Grid>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<TextBox x:Name="Money" Height="100" Header="Enter your money"/>
<Button
x:Name="MyBtn"
Click="Button_Click"
Content="Ok"
Margin="30"/>
</StackPanel>
</Grid>
頁面 1.xaml.cs
public partial class Page1 : Page
{
public Page1()
{
this.InitializeComponent();
}
public delegate void PaymentEventHandler(object sender, EventArgs args);
public event PaymentEventHandler SuccessfullPayment;
protected virtual void OnSuccessfullPayment()
{
if (SuccessfullPayment != null)
{
SuccessfullPayment(this, EventArgs.Empty);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//in case that payment is successful (this logic is unnecesary in this example)
OnSuccessfullPayment();
this.Frame.Navigate(typeof(MainBankPage));
}
}
第 2 頁.xaml
<Grid>
<ScrollViewer>
<StackPanel x:Name="RootLayout" Orientation="Vertical" />
</ScrollViewer>
</Grid>
頁面 2.xaml.cs
public sealed partial class Page2 : Page
{
public Page2()
{
this.InitializeComponent();
}
public void Initialization()
{
var payment= new Page1();
payment.SuccessfullPayment += CreateTextBlock;
}
public void CreateTextBlock(object sender, EventArgs e)
{
var textblock = new TextBlock();
textblock.Margin = new Thickness(0, 20, 15, 0);
textblock.Width = 400;
textblock.Height = 60;
textblock.FontSize = 20;
textblock.HorizontalAlignment = HorizontalAlignment.Left;
textblock.Text = "Payment was successfull";
RootLayout.Children.Add(textblock);
}
}
主頁
只有 6 個按鈕可供用戶交互以在我的應用程序中的頁面之間導航,因此我認為沒有必要顯示代碼
我試圖通過自定義事件來做到這一點(它在示例中顯示),但沒有奏效。
我在應用程序開發方面有點新,所以如果這是愚蠢的方式,我願意接受其他選擇
注意:我的應用程序要復雜得多我只想知道如何做這個特定的事情所以我創建了這個簡單的例子:)
如果不發表評論,希望一切都清楚,我會盡力改進問題。
非常感謝您的時間和答案。
如果沒有人注冊來處理它,那么引發事件就毫無意義。 如果我正確理解您的問題,則在您從Page1
引發事件時沒有創建Page2
,因此這將不起作用。
您可以將信息存儲在某個全局對象中,而不是引發事件,該對象可以隨時從應用程序的任何位置訪問。
例如,您可以創建一個靜態類:
public static class AppInfo
{
public static string SharedInfo { get; set; }
}
...並從任何頁面獲取和設置它的屬性,例如:
第1頁:
private void Button_Click(object sender, RoutedEventArgs e)
{
//in case that payment is successful (this logic is unnecesary in this example)
AppInfo.SharedInfo = "Payment was successfull";
OnSuccessfullPayment();
this.Frame.Navigate(typeof(MainBankPage));
}
第2頁:
public void Initialization()
{
var textblock = new TextBlock();
textblock.Margin = new Thickness(0, 20, 15, 0);
textblock.Width = 400;
textblock.Height = 60;
textblock.FontSize = 20;
textblock.HorizontalAlignment = HorizontalAlignment.Left;
textblock.Text = AppInfo.SharedInfo;
RootLayout.Children.Add(textblock);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.