Obtenir MVVM ViewModel de se lier à la vue
-
22-09-2019 - |
Question
Je le code suivant (noms d'objets modifiés, des erreurs si la syntaxe / d'orthographe ignorer).
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; }
}
Voici le code que j'ai dans codebehind ma page.
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");
}
Enfin, voici un échantillon de ce que mon XAML ressemble.
<!--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>
Est-ce que je fais mal ici?
La solution
Je pense que votre ViewModel devrait implémenter l'interface INotifyPropertyChanged:
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Alors votre propriété ressemblerait que:
private title;
public string Title
{
get
{
return this.title;
}
set
{
if (this.title!= value)
{
this.title= value;
this.RaisePropertyChanged("Title");
}
}
}
Michael
Autres conseils
Eh bien, allez comprendre, 10 minutes après que je poste, je le comprendre.
Je manquais la mise en œuvre de INotifyProperty. Merci si quelqu'un est à la recherche à ce sujet.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow