链接c中的TextBlock和TextBox
本文关键字:TextBox TextBlock 中的 链接 | 更新日期: 2023-09-27 18:10:54
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>
现在我想将用户提供的名称转移到文本块,这样它就可以更改默认名称,即"玩家1回合">
主页.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"&但是我无法访问文本块的用户输入数据!
您需要将值从login.xaml页面传递到MainPage.xaml。没有其他方法可以直接将值绑定到放置在不同页面上的控件。
- 我希望您在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;
}
- 另一种方法是,取一个全局变量,并将文本框值分配给它,然后将相同的值分配给另一页上的文本块
MVVM解决方案:
视图模型:
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
,并将我的信息添加为
public static Info myInfo = new Info()
在每个页面中添加this.DataContext = Helper.my
或创建属性Info do this.Info = Helper.myInfo
并绑定它,或者也可以执行TextBlock.Text = Helper.myInfo.Player1Name
如果你喜欢