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

标签 c# wpf xaml textbox

我是 WPF 的新手,我想知道是否有人可以帮助我解决我遇到的这个问题。 我正在尝试让我的 TextBox 能够为字符串变量赋值。

这是 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; 就足够了,但它不会在文本区域中显示变量。

如果有人可以帮助我,我将不胜感激。

最佳答案

Button Click 处理程序应直接设置 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;
    }
}

关于c# - 如何让我的 WPF 文本框在变量中插入值并将其显示在文本区域中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52871342/

相关文章:

c# - 使用两个参数来线程化子进程?

c# - 编码字符 *

c# - MEF 是一件全有还是全无的事情吗?

c# - XAML UI 更新在代码隐藏中不可见

c# - WPF 列表框项位图图像更新

c# - 手动添加文件后尝试访问 uwp 发布者缓存的 UnauthorizedAccessException

c# - 在 Xamarin.forms C# 中显示包含 JSON 数据的列表

c# - LiveChart 不显示 x 轴 WPF 上的所有标签

c# - 从 XAML 中删除重复的 DataTrigger 代码

c# - WPF 中带有文本 block 的动态工具提示