如何让我的 WPF 文本框在变量中插入值并将其显示在文本区域中?



我对WPF很陌生,我想知道是否有人可以帮助我解决我遇到的这个问题。 我正在尝试让我的文本框能够为字符串变量提供值。

这是 C# 代码:

public partial class MainWindow : Window
{
string player;
public string PlayerName
{
get { return (string)GetValue(Property); }
set { SetValue(Property, value); }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
player = user.Text;
}
public static readonly DependencyProperty Property =
DependencyProperty.Register("PlayerName", typeof(string), typeof(MainWindow), new PropertyMetadata(string.Empty));
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
this.PlayerName = player;
}
}

这是 Xaml 代码:

<Window x:Class="memorytest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:memorytest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBlock Text="{Binding Path=PlayerName, UpdateSourceTrigger=PropertyChanged}" Margin="10,10,199.6,240" />
<TextBox x:Name="user" VerticalAlignment="Center" />
<Button Content="Click Me" VerticalAlignment="Bottom" Click="Button_Click" />  
</Grid>

从我读过的其他来源来看,似乎player = user.Text;就足够了,但它不会在文本区域中显示变量。

如果有人能帮我解决这个问题,我将不胜感激。

按钮单击处理程序应直接设置PlayerName属性。不需要player字段。

public partial class MainWindow : Window
{
public string PlayerName
{
get { return (string)GetValue(Property); }
set { SetValue(Property, value); }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
PlayerName = user.Text;
}
public static readonly DependencyProperty Property =
DependencyProperty.Register("PlayerName", typeof(string), typeof(MainWindow), new PropertyMetadata(string.Empty));
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
}

最新更新