簡體   English   中英

如何將文本框的文本獲取到另一個 xaml 中的文本塊? c# windows store app

[英]How to get the text of textbox to textblock in another xaml? c# windows store app

我的 MainPage.xaml 中的代碼

<TextBox x:Name="txtBox1" HorizontalAlignment="Left" 
        Margin="376,350,0,0" TextWrapping="Wrap" 
        VerticalAlignment="Top" Height="14" Width="113" 
        Text="{Binding TextBox1Text}"/>

我的 MainPage.xaml.cs 中的代碼

public string TextBox1Text
{
    get { return this.txtBox1.Text; }
    set { this.txtBox1.Text = value; }
}   

我的 Page2.xaml 中的代碼

MainPage main = new MainPage();
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    txtBlock1.Text = main.TextBox1Text;
}

當我運行它時,我的文本塊中沒有輸出文本

一種更簡單的方法是在頁面之間傳遞參數:

MainPage.xaml.cs

private void Button_Click(object sender, RoutedEventArgs e)
{
    Frame.Navigate(typeof(Page2), textBox1.Text);
}

Page2.xaml.cs

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    textBlock1.Text = e.Parameter.ToString();
}

編輯:看來您要傳遞多個參數。 您可以在List<T>集合中打包多個對象或創建一個類:

public class NavigationPackage
{
    public string TextToPass { get; set; }
    public ImageSource ImgSource { get; set; }
}

在您當前的頁面中:

private void Button_Click(object sender, RoutedEventArgs e)
{
    NavigationPackage np = new NavigationPackage();
    np.TextToPass = textBox1.Text;
    np.ImgSource = bg2.Source;

    Frame.Navigate(typeof(MultiGame), np);
 }

MultiGame.cs您可以“解包”類中的項目:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    NavigationPackage np = (NavigationPackage)e.Parameter;

    newTextBlock.Text = np.TextToPass;
    newImage.Source = np.ImgSource;
}

您正在創建MainPage的新實例。 TextBox1Text未使用值進行初始化。

如果您希望它成為所有頁面共享的值,請創建一個靜態類或在 App.cs 文件中聲明您的屬性

這和說是一樣的。

MyCustomClass x = new MyCustomClass();
x.StringProperty = "Im set";

x = new MYCustomClass();

x.StringProperty現在沒有設置。

試試這個:在 MainPage.cs

public static MainPage current;

public static Textbox txtbox

Public mainpage()
{
     Current = this;
     txtbox = this.yourtextboxInXAML;
}

在 page2.cs

public Mainpage.Current.txtbox txtbox;

現在,您可以隨時在 page2 中使用 Mainpage XAML 文本框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM