Conseguir MVVM modelo de vista que se unen a la vista
-
22-09-2019 - |
Pregunta
Tengo el siguiente código (nombres de objeto cambiado, por lo que los errores de sintaxis / ortografía ignoran).
public class ViewModel
{
ViewModelSource m_vSource;
public ViewModel(IViewModelSource source)
{
m_vSource= source;
m_vSource.ItemArrived += new Action<Item>(m_vSource_ItemArrived);
}
void m_vSource_ItemArrived(Item obj)
{
Title = obj.Title;
Subitems = obj.items;
Description = obj.Description;
}
public void GetFeed(string serviceUrl)
{
m_vFeedSource.GetFeed(serviceUrl);
}
public string Title { get; set; }
public IEnumerable<Subitems> Subitems { get; set; }
public string Description { get; set; }
}
Este es el código que tengo en mi código subyacente de la página.
ViewModel m_vViewModel;
public MainPage()
{
InitializeComponent();
m_vViewModel = new ViewModel(new ViewModelSource());
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
this.DataContext = m_vViewModel;
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
m_vViewModel.GetItems("http://www.myserviceurl.com");
}
Por último, he aquí una muestra de lo que mis xaml se parece.
<!--TitleGrid is the name of the application and page title-->
<Grid x:Name="TitleGrid" Grid.Row="0">
<TextBlock Text="My Super Title" x:Name="textBlockPageTitle" Style="{StaticResource PhoneTextPageTitle1Style}"/>
<TextBlock Text="{Binding Path=Title}" x:Name="textBlockListTitle" Style="{StaticResource PhoneTextPageTitle2Style}"/>
</Grid>
¿Hay algo que estoy haciendo mal aquí?
Solución
Creo que su modelo de vista debe implementar la interfaz INotifyPropertyChanged:
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
A continuación, su propiedad se vería así:
private title;
public string Title
{
get
{
return this.title;
}
set
{
if (this.title!= value)
{
this.title= value;
this.RaisePropertyChanged("Title");
}
}
}
Michael
Otros consejos
Bueno, vaya usted a saber, 10 minutos después de lo pongo, lo averigüe.
Me faltaba la implementación INotifyProperty. Gracias si alguien está buscando en este.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow