我有一个参数“name”,“location”(或“room”,如果你想要的话)和“location2”(或“floor”)的数据集,如下所示:
Location2 Location Name
1st floor Living room Lights
1st floor Living room Temperature
1st floor Living room Thermostat
1st floor Kitchen Lights
2nd floor Bedroom Lights
等等。
我有两个分别绑定到Location2和Location的ComboBox。 “位置”的项目取决于选择“位置2”。当您首先选择一个楼层(“位置”)然后选择一个房间(“位置”)时,您将获得所选房间中的所有设备。
这很好用,就像这样:
<ComboBox x:Name="Location2Combobox" Margin="5,10,5,5" Width="120" ItemsSource="{x:Bind ViewModel.Location2, Mode=OneWay}" SelectedValue="{x:Bind ViewModel.Location2Filter, Mode=TwoWay}" />
<ComboBox x:Name="Location1Combobox" Margin="5,10,5,5" Width="120" ItemsSource="{x:Bind ViewModel.Location1, Mode=OneWay}" SelectedValue="{x:Bind ViewModel.Location1Filter, Mode=TwoWay}" />
组合框在OnNavigatedToAsync()
上进行数据绑定public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
{
....
if (Location2 == null) Location2 = (from d in App.HS.DeviceList
orderby d.location2 ascending
select d.location2).Distinct().ToList();
if (Location1 == null) Location1 = (from d in App.HS.DeviceList
where d.location2 == Location2Filter
orderby d.location ascending
select d.location).Distinct().ToList();
}
...但是当Location2Filter更新时,Location1Combobox的数据源也会更新。 (当用户选择楼层时,会更新房间的组合框。)
string _Location2Filter = "";
public string Location2Filter
{
get { return _Location2Filter; }
set
{
Set(ref _Location2Filter, value);
UpdateLocation1();
}
}
public void UpdateLocation1()
{
Debug.WriteLine("MainPageViewModel UpdateLocation1(), navigateBack: " + navigateBack.ToString());
if (Location2Filter != "")
{
Location1 = (from d in App.HS.DeviceList
where d.location2 == Location2Filter
orderby d.location ascending
select d.location).Distinct().ToList();
}
}
这一切都运作良好! :)
但是,当我点击ListItem时,我会导航到一个新页面。 但是当我回去时,房间组合框被重置了! 由于NavigationCacheMode,楼层组合框选择最后选择的值。但不是房间组合框。
我无法绕过我需要做的事情。
答案 0 :(得分:1)
我做了一个演示并重现了你的问题。在调试过程中,我发现问题出在以下代码中:
public string Location2Filter
{
get { return _Location2Filter; }
set
{
Set(ref _Location2Filter, value);
UpdateLocation1();
}
}
每次导航到新页面时,都会调用updateLocation()
,这会导致location1组合框清空。
要解决此问题,您可以编辑如下代码:
public string Location2Filter
{
get { return _Location2Filter; }
set
{
if (_Location2Filter != value) {
Set(ref _Location2Filter, value);
UpdateLocation1();
}
}
}