我是MVVM的新手并且一直试图将工作程序转换为MVVM程序。 我一直在寻找答案,但到目前为止还没有运气。
基本上我拥有的是:列表框和列表视图。列表框中填充了Trainstations,我想在列表视图中显示站点的时间(有延迟等)。列表框中充满了工作站,每当我选择一个工作站时,它都会更新,我将它放在一个名为“CurrentStation”的变量中。现在我正在使用这个'CurrentStation'来获取该站所有离开的ObservableCollection列表,但由于某种原因,该功能只被调用一次,当我选择另一个站时不会更新。
我也不知道在xaml代码中绑定什么。
<ListBox x:Name="lstStations" Margin="8" Grid.Row="1" ItemsSource="{Binding StationList}" SelectedItem="{Binding CurrentStation}" DisplayMemberPath="Name"/>
<ListView Grid.Column="1" Margin="8" Grid.Row="1" ItemsSource="{Binding Departures}" >
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Time, StringFormat=t}" Header="Time" />
<GridViewColumn DisplayMemberBinding="{Binding Delay, Converter={StaticResource mijnDelayConverter}}" Header="Delay"/>
<GridViewColumn DisplayMemberBinding="{Binding Station}" Header="Station"/>
<GridViewColumn DisplayMemberBinding="{Binding Vehicle}" Header="Vehicle"/>
<GridViewColumn Header="Platform" CellTemplate="{DynamicResource dataTemplateTextblock}" />
<!-- Haven't had the chance to look at this ^ I don't think this is correct though -->
</GridView>
</ListView.View>
</ListView>
这是ViewModel代码:
public string Name
{
get
{
return "MainPage";
}
}
public ObservableCollection<Station> StationList
{
get
{
return Station.GetStations();
}
}
private Station _currentStation;
public Station CurrentStation
{
get
{
return _currentStation;
}
set
{
_currentStation = value;
Console.WriteLine("New station selected: " + _currentStation.ToString());
OnPropertyChanged("CurrentStation");
}
}
private ObservableCollection<Departure> _departures;
public ObservableCollection<Departure> Departures
{
get
{
return Departure.GetDepartures(CurrentStation);
}
set
{
_departures = value;
}
}
答案 0 :(得分:3)
我认为你需要:
明确更新Departures
属性,可以在CurrentStation
setter中完成
private Station _currentStation;
public Station CurrentStation
{
get
{
return _currentStation;
}
set
{
_currentStation = value;
Departures = Departure.GetDepartures(_currentStation);
Console.WriteLine("New station selected: " + _currentStation.ToString());
OnPropertyChanged("CurrentStation");
}
}
触发更改通知,该更改通知将使用着名的OnPropertyChanged
private ObservableCollection<Departure> _departures;
public ObservableCollection<Departure> Departures
{
get
{
return _departures
}
set
{
_departures = value;
OnPropertyChanged("Departures");
}
}
答案 1 :(得分:0)
您必须将Observable集合上的OnPropertyChanged设置为
public ObservableCollection<Departure> Departures
{
get
{
return Departure.GetDepartures(CurrentStation);
}
set
{
_departures = value; OnPropertyChanged("Departures")
}
}