Reputation: 1334
Maybe this is awfully wrong. I have a text box and want the value in that text box to be synchronized with a member of a class. I thought I use binding but I cannot get a handle on it. What I tried is below and does not work. Where am I thinking wrong?
Here is my XAML:
<Window x:Class="tt_WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:tt_WPF"
Title="MainWindow" SizeToContent="WidthAndHeight">
<StackPanel>
<TextBox x:Name="tb" Width="200" Text="{Binding local:abc.Name}"></TextBox>
<Button Click="Button_Click">Ok</Button>
</StackPanel> </Window>
And here the code behind:
public class ABC
{
public string Name { get; set; }
}
public partial class MainWindow : Window
{
private ABC abc = new ABC();
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{ }
}
Upvotes: 2
Views: 8804
Reputation: 3101
First, implement INotifyPropertyChanged and raise the property changed event on ABC.Name.
You'll want to set the ABC object in your MainWindow.cs as the data context and bind Name to TextBox.Text
. In the code-behind:
public ABC MyABC { get; set; }
public MainWindow()
{
InitializeComponent();
MyABC = new ABC();
DataContext = MyABC;
}
And bind in XAML:
<TextBox x:Name="tb" Width="200" Text="{Binding Name, UpdateSourceTrigger="PropertyChanged"}"/>
Upvotes: 5