【发布时间】:2020-05-02 18:00:22
【问题描述】:
我正在尝试做一个从 List 加载 ItemSource 并根据外部事件根据 Local.id 更改其 SelectedIndex 的选择器,但到目前为止我一直在尝试的方法不起作用。
C#代码:
public class Local
{
public string cidade { get; set; }
public int id { get; set; }
}
public int CidadeSelectedIndex{ get; set; }
string jsonCidades;
public async void CarregaCidades()
{
try
{
using (WebClient browser = new WebClient())
{
Uri uriCidades = new Uri("xxxxxxx.php");
jsonCidades = await browser.DownloadStringTaskAsync(uriCidades);
}
var ListaCidades = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Local>>(jsonCidades);
PickerCidades.ItemsSource = ListaCidades;
}
catch (Exception)
{
throw;
}
}
//In some moment of the execution, this code is called:
Local localizacao = JsonConvert.DeserializeObject<Local>(json);
if (localizacao.GetType().GetProperty("id") != null)
{
/*CidadeSelectedItem = localizacao;
I tried that before with SelectedItem="{Binding CidadeSelectedItem, Mode=TwoWay}" */
CidadeSelectedIndex = localizacao.id; // now trying this
}
在我尝试使用 ItemDisplayBinding="{Binding ListaCidades.cidade, Mode=OneWay}" 进行绑定之前,但由于它不起作用,我开始使用 ItemSources=ListaCidades
我的 XAML 代码:
<Picker x:Name="PickerCidades"
SelectedIndex="{Binding CidadeSelectedIndex, Mode=TwoWay}"
Grid.Column="1" Grid.Row="0"
SelectedIndexChanged="PickerCidades_SelectedIndexChanged">
</Picker>
我认为它不起作用,因为我正在使用 ItemsSource 设置项目。我想我需要使用 xaml 绑定它。能帮上忙就好了。
【问题讨论】:
-
你在使用 INotifyPropertyChanged 吗?
-
没有。我正在调用一个更改 CidadeSelectedIndex 值的方法
-
如果您不使用 INPC,更改 SelectedIndex 变量的值不会更新 UI
-
@Jason 如果我使用“INPC”,是否可以通过更改 SelectedIndex 来更改 ui?