簡體   English   中英

在C#XAML中鏈接TextBlock和TextBox

[英]Linking TextBlock and TextBox in c# xaml

login.xaml

<TextBox x:Name="player1"  HorizontalAlignment="Left" Margin="544,280,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Height="44" Width="280"  CacheMode="BitmapCache" FontFamily="Century Schoolbook" FontSize="26">
        <TextBox.Foreground>
            <SolidColorBrush Color="White" />
        </TextBox.Foreground>
        <TextBox.Background>
            <SolidColorBrush Color="#FF1EA600" Opacity="0.645"/>
        </TextBox.Background>
    </TextBox>

現在我想將用戶提供的名稱轉移到textblock,以便它可以更改默認名稱“ player 1 turn”

MainPage.xaml

<TextBlock x:Name="playerTurn" TextWrapping="Wrap" Text="Player 1 Turn" VerticalAlignment="Top" Height="70" FontSize="50" 
            Foreground="Cyan" TextAlignment="Center" FontFamily="Century Gothic" />

因此,我創建了兩個不同的頁面,其中一個是“ login.xaml”和“ MainPage.xaml”,但是我無法訪問用戶輸入的數據到textblock!

您需要將值從login.xaml頁面傳遞到MainPage.xaml。 沒有其他方法可以將值直接綁定到放置在不同頁面上的控件。

  1. 我希望您在login.xaml頁面上有一些按鈕單擊事件處理程序。 在導航到頁面時傳遞值,然后在另一個頁面上獲取值。

發送(login.xaml):

string s = player1.Text;
this.Frame.Navigate(typeof(MainPage),s );

接收(MainPage.xaml):

protected override void OnNavigatedTo(NavigationEventArgs e)
{
   string s = Convert.ToString(e.Parameter);
   playerTurn.Text = s;
}
  1. 另一種方法是,獲取全局變量並為其分配文本框值,然后將相同的值分配給另一頁上的文本塊。

MVVM解決方案:

ViewModel:

public string PlayerName { get; set; }
public ICommand LoginCommand { get; private set; }

private void OnLogin(object obj)
{
    //STORE PlayerName in Global Context and after navigate to MainPage, read it.
    GlobalContext.PlayerName = this.PlayerName;
    this.Frame.Navigate(typeof(MainPage));
}

private bool CanLogin(object arg)
{
    return string.IsNullOrEmpty(PlayerName) ? false : true;
}

public CONSTRUCTOR()
{
    LoginCommand = new DelegateCommand<object>(OnLogin, CanLogin);
}

Xaml:

<TextBox Width="100" Height="20" Text="{Binding PlayerName, Mode=TwoWay}"></TextBox>
<Button Content="Login" Command="{Binding LoginCommand}"></Button>

我不知道最佳做法,但是當我想從許多頁面訪問許多信息時:

我創建一個public class Info ,一個public static class Helper ,並將我的Info添加為

public static Info myInfo = new Info()

並在每個頁面中添加this.DataContext = Helper.my或創建一個屬性Info來做到這一點this.Info = Helper.myInfo並將其綁定,或者也可以執行TextBlock.Text = Helper.myInfo.Player1Name

如果您願意,我會添加一些代碼

暫無
暫無

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

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