Как получить текстовое поле WPF для вставки значения в переменную и отображения его в текстовой области? - PullRequest
0 голосов
/ 18 октября 2018

Я довольно новичок в 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;, но переменная в текстовой области не будет отображаться.

Если кто-томог бы помочь мне с этим, я был бы признателен.

1 Ответ

0 голосов
/ 18 октября 2018

Обработчик нажатия кнопки должен непосредственно устанавливать свойство 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;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...