I have below xaml file (this a piece):
<Grid Opacity="1" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="ID"/>
<Label Grid.Row="0" Grid.Column="1" Content="Name"/>
<Label Grid.Row="0" Grid.Column="2" Content="Description"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding ID}"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Name}"/>
<TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding Description}"/>
</Grid>
Below the Data Class:
public class Data : INotifyPropertyChanged
{
private string id= string.Empty;
private string name = string.Empty;
private string description = string.Empty;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string ID
{
get
{
return this.id;
}
set
{
if (value != this.id)
{
this.id = value;
NotifyPropertyChanged("ID");
}
}
}
public string Name
{
get
{
return this.name;
}
set
{
if (value != this.name)
{
this.name = value;
NotifyPropertyChanged("Name");
}
}
}
public string Description
{
get
{
return this.description;
}
set
{
if (value != this.description)
{
this.description = value;
NotifyPropertyChanged("Description");
}
}
}
}
Also in xaml.cs I implement INotifyPropertyChanged:
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
Furthermore, in the above xaml I have a button defined as:
<Button Click="btn_Click"/>
and the implementation for that is in xaml.cs as below:
private void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
(DataContext as MyViewModel).SearchInDb('0303003'); // 0303003 -> this is only an example.
}
On button click a method on MyViewModel class is called, and from there it invokes a query to database to retrieve data using ID = 0303003.
Below MyViewModel class (I show only the method):
public void SearchInDb(string id)
{
// request data to sql server database
// and then populate a Data Class Object with the data retrieved
// from database:
Data = new Data(){
ID = sReader[0].ToString().Trim(),
Name = sReader[1].ToString().Trim(),
Description = sReader[2].ToString().Trim()
};
}
Note: MyViewModel class does not implement INotifyPropertyChanged.
My problem is the following:
After populating a new Data object within above method "SearchInDb", my labels in the grid are not updated, they remain empty.
See Question&Answers more detail:
os