I am quite new to WPF and I am wondering if someone could help me with this problem I am having. I am trying to get my TextBox to be able to give a value to a string variable.
This is the C# code:
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;
}
}
And this is the Xaml code:
<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>
From other sources that I have read it seems that player = user.Text;
is enough for that, but it won't display the variable in the textarea.
If someone could help me with this I would appreciate it.
The Button Click handler should directly set the PlayerName
property. The player
field is not needed.
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;
}
}