gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:09:56 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com