I’m trying to build up a page that will show a progress bar until the data is successfully downloaded from a server.
For this i use a Generic data downloader that will simply populate the Model’s properties and set the IsLoading property to true and/or false
The View models look like:
public class GenericPageModel: GenericModel
{
private bool _isLoading;
public bool IsLoading
{
get { return _isLoading; }
set
{
_isLoading = value;
OnPropertyChanged("IsLoading");
}
}
}
public class GenericModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
The GenericPageModel is used in a XAML page as a Model and the IsLoading property is used as bellow:
<Grid>
<Grid.Resources>
<BooleanToVisibilityConverter x:Key="boolToVis"/>
</Grid.Resources>
<ProgressBar Height="25" Margin="5"
VerticalAlignment="Center" HorizontalAlignment="Stretch"
Visibility="{Binding IsLoading, Converter={StaticResource boolToVis}}"
IsIndeterminate="True"
/>
</Grid>
The generic data downloader:
...
// Model that it's calling this
public object Model
{ get; set; }
private string _loadingProperty;
...
void _bw_DoWork(object sender, DoWorkEventArgs e)
{
// Set the is loading property
if (null != _loadingProperty)
{
//((Model as GenericModel).Owner as GenericPageModel).IsLoading = true; // Works!!
Model.GetType().GetProperty(_loadingProperty).SetValue(Model, true, null); // Doesn't work
}
}
If i explicitly cast Model to the GenericPageModel and set the IsLoading to true, everything works just fine (see the commented line)
If i use reflection to set the Value of the property, the IsLoading setter is hit correctly, the OnPropertyChanged method is called ok, but the UI doesn’t update
Is there something extra that needs to be done when setting a property trough reflection? I ‘m guessing the Events aren’t raised properly but i can’t figure out what to do.
Solved there was an extra model inserted before the downloader call, the line should’ve said:
object Owner = Model.GetType().GetProperty("Owner").GetValue(Model, null);
Model.GetType().GetProperty(_loadingProperty).SetValue(Owner, true, null);
The following lines
are not equivalent. The first affects the
IsLoadingproperty on theModel.Ownerobject, the second on theModelobject itself.Note: your ViewModel base class really shouldn’t be called
GenericModelas it’s the ViewModel, not the Model.