gpt4 book ai didi

c# - mvvm 绑定(bind) selecteditem 以更新 ListView

转载 作者:行者123 更新时间:2023-12-03 10:23:23 27 4
gpt4 key购买 nike

我是 MVVM 的新手,一直在尝试将工作程序转换为 MVVM 程序。
我一直在为此寻找答案,但到目前为止还没有任何运气。

基本上我所拥有的是:一个列表框和一个 ListView 。列表框充满了火车站,我想要 ListView 中的车站时间(有延迟等)。列表框充满了电台,每当我选择一个电台时,它都会更新,我将它放在一个名为“CurrentStation”的变量中。现在我正在使用这个“CurrentStation”来获取所有从该车站出发的 ObservableCollection 列表,但由于某种原因,该函数只被调用一次,并且在我选择另一个车站时不会更新。

我也不知道在 xaml 代码中绑定(bind)什么。

<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;
}
}

最佳答案

我认为你需要:

  • 更新 Departures明确的属性,它可以在 CurrentStation 内完成二传手
    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 刷新您的离开绑定(bind)(和列表框!)
    private ObservableCollection<Departure> _departures;
    public ObservableCollection<Departure> Departures
    {
    get
    {
    return _departures
    }
    set
    {
    _departures = value;
    OnPropertyChanged("Departures");
    }
    }
  • 关于c# - mvvm 绑定(bind) selecteditem 以更新 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19577978/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com