MVVM 绑定选定项以更新列表视图
本文关键字:更新 列表 视图 绑定 MVVM | 更新日期: 2023-09-27 18:36:56
我是MVVM的新手,一直在尝试将工作程序转换为MVVM程序。我一直在寻找答案,但到目前为止没有任何运气。
基本上我拥有的是:一个列表框和一个列表视图。列表框中充满了火车站,我希望在列表视图中显示车站的时间(有延迟等)。列表框中充满了电台,每当我选择一个电台时,它都会更新,并且我将其放在一个名为"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>
下面是视图模型代码:
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;
}
}
我认为你需要:
-
显式更新
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"); } }
你也必须在 Observabe 集合上设置 OnPropertyChanged
public ObservableCollection<Departure> Departures
{
get
{
return Departure.GetDepartures(CurrentStation);
}
set
{
_departures = value; OnPropertyChanged("Departures")
}
}