[英]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。 沒有其他方法可以將值直接綁定到放置在不同頁面上的控件。
發送(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;
}
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.