Reputation: 5246
i want to bind textbox But it isn't display the string. Second thing is i want to update Name string periodically. Any solution?
here is my c# code:
public partial class Window1 : Window
{
public String Name = "text";
}
xaml code:
<Grid Name="myGrid" Height="300">
<TextBox Text="{Binding Path=Name}"/>
</Grid>
Upvotes: 0
Views: 177
Reputation: 12315
public partial class MainWindow : Window,INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
NotifyCahnge("Name");
}
}
private void NotifyChange(string prop)
{
if(PropertyChanged!=null)
PropertyChanged(this,new PropertyChangedEventArgs(prop));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Hope this will help
Upvotes: 3
Reputation: 3996
You need to delcare Properties not field, what you have delcared here is a field.
public String Name {get; set;}
Plus it should not be in the Control file (UI file). Move it to separate class and set it as a DataContext.
PLus as Vlad pointed you need to Notify to UI that things changes, simple proprties doesn't have that.
Nice article on dataBinding :
Upvotes: 2
Reputation: 35594
You need to define your Name
as a DependencyProperty
:
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(Window1));
(Note that Visual Studio defines a handy snippet propdp
for this, try typing propdp
+ TAB + TAB.)
Then, you need to bind correctly. Something like that:
<TextBox Text="{Binding Name, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"/>
Upvotes: 1
Reputation: 22747
WPF bindings work with properties, not fields. You need to define Name
as a property, and also set the Window's data context:
public partial class Window1 : Window
{
public String Name { get; set; }
public Window1()
{
Name = "text";
DataContext = this;
InitializeComponent();
}
}
You can also define it as a Dependency Property if you want to support change notification and other DP-related features or use INotifyPropertyChanged
. I suggest you read more about WPF data binding here.
Upvotes: 1