简体   繁体   English

结果未出现在选择器Xamarin.Forms中

[英]Results not appearing in picker Xamarin.Forms

I have a code scanner that after scans, it returns me a string value. 我有一个代码扫描仪,扫描后,它返回一个字符串值。 Then I add this string value to an observable collection. 然后,我将此字符串值添加到一个可观察的集合中。

When the ScanCode() method is triggered, the camera opens up and it scans a code then adds the value to the list. 触发ScanCode()方法时,相机会打开并扫描代码,然后将值添加到列表中。 Then it gets back to the page, but the picker remains empty. 然后返回页面,但选择器仍然为空。 Kindly help to figure out the issue. 请帮助解决问题。

private ObservableCollection<string> _codes;
public ObservableCollection<string> Codes
{
    get { return _codes; }
    set
    {
        _codes = value;
        OnPropertyChanged();
    }
}


public async void ScanCode()
{

    codes= new ObservableCollection<string>();

    var cd = await CodeScanViewModel.CodePage1(); // returns the code in string

    if (cd != null)
    {

        _codes.Add(cd.ToString());             
    }
}

Then in my XAML, I have defined the picker as follows: 然后在我的XAML中,如下定义了选择器:

            <Picker
                Title="Codes" 
                ItemsSource="{Binding Codes}"
                VerticalOptions="Center" />

At this point, as you have set a new instance of collection to _codes but the didn't raise the property-changed notification. 至此,您已经将新的collection实例设置为_codes但是没有引发属性更改的通知。 So the Picker control is still listening to the older instance for collection-changed events. 因此, Picker控件仍在侦听旧实例的集合更改事件。 In order to fix that, make sure to use: 为了解决此问题,请确保使用:

public async void ScanCode()
{
    Codes = new ObservableCollection<string>();
...

Or, 要么,

public async void ScanCode()
{
    _codes = new ObservableCollection<string>();
     OnPropertyChanged(nameof(Codes));
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM