Suppression State Error CS0266 Cannot implicitly convert type '' to 'System.Collections.IEnumerable'

Someguy

Hi i'm trying to pull a single product instead of multiple I found the Wrapper WoocomNet has a get instead of GetAll method so I'm passing the ID and trying to load it im getting the correct id but cant load it into my listview Going to Show my Code the XAML and The Wrapper Method


  async void ProductClicked(object sender, EventArgs args)
        {

            var btn = (Button)sender;
            var productid = btn.BindingContext;

            RestAPI rest = new RestAPI("site.com/wp-json/wc/v3/""key""secret")
             WCObject wc = new WCObject(rest);
            var p = await wc.Product.Get(Convert.ToInt32(productid));


            productsListView.ItemsSource = p;
}

Xaml


 <ListView x:Name="productsListView"
                      HasUnevenRows="True"                       
                  VerticalOptions="FillAndExpand"
                      SeparatorVisibility="None">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.View>
                                <Frame HasShadow="True" Margin="8">
                                    <StackLayout>
                                        <Label x:Name="something" Text="{Binding name}" FontSize="Large"/>
                                        <Image Source="{Binding ProductImage.src}"/>
                                        <Label Text="{Binding date_created, StringFormat='{0:dd/MM/yyyy}'}" FontSize="Small" FontAttributes="Italic"/>
                                        <Label Text="{Binding price }"/>
                                        <Label Text="{x:Binding enable_html_description  }" FontSize="Medium"/>
                                        <Label Text="{x:Binding sku}" FontSize="Medium"/>
                                        <Button BindingContext="{Binding id}" Clicked="ProductClicked"></Button>
                                    </StackLayout>
                                </Frame>

                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

Wrapper



namespace WooCommerceNET.Base
{
    public class WCItem<T>
    {
        public WCItem(RestAPI api);

        public string APIEndpoint { get; protected set; }
        public RestAPI API { get; protected set; }

        [AsyncStateMachine(typeof(WCItem<>.<Add>d__12))]
        public Task<T> Add(T item, Dictionary<string, string> parms = null);
        [AsyncStateMachine(typeof(WCItem<>.<AddRange>d__13))]
        public Task<BatchObject<T>> AddRange(BatchObject<T> items, Dictionary<string, string> parms = null);
        [AsyncStateMachine(typeof(WCItem<>.<Delete>d__17))]
        public Task<T> Delete(int id, bool force = false, Dictionary<string, string> parms = null);
        [AsyncStateMachine(typeof(WCItem<>.<DeleteRange>d__18))]
        public Task<string> DeleteRange(BatchObject<T> items, Dictionary<string, string> parms = null);
        [AsyncStateMachine(typeof(WCItem<>.<Get>d__9))]
        public Task<T> Get(int id, Dictionary<string, string> parms = null);
        [AsyncStateMachine(typeof(WCItem<>.<Get>d__10))]
        public Task<T> Get(string email, Dictionary<string, string> parms = null);
        [AsyncStateMachine(typeof(WCItem<>.<GetAll>d__11))]
        public Task<List<T>> GetAll(Dictionary<string, string> parms = null);
        [AsyncStateMachine(typeof(WCItem<>.<Update>d__14))]
        public Task<T> Update(int id, T item, Dictionary<string, string> parms = null);
        [AsyncStateMachine(typeof(WCItem<>.<UpdateRange>d__16))]
        public Task<BatchObject<T>> UpdateRange(BatchObject<T> items, Dictionary<string, string> parms = null);
        [AsyncStateMachine(typeof(WCItem<>.<UpdateWithNull>d__15))]
        public Task<T> UpdateWithNull(int id, object item, Dictionary<string, string> parms = null);
    }
}

My Error code:Severity Code Description Project File Line Suppression State Suppression State Error CS0266 Cannot implicitly convert type 'WooCommerceNET.WooCommerce.v3.Product' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?) Ecombeta \Products.xaml.cs 68 Active

I just need productlistview's source to be set to p But i'm not sure how these cast's work

If anyone would borrow a minute i'd really appreciate it.

Thank you

Also for Ref going to show the get all way


 private async Task InitAsync()
        {




            RestAPI rest = new RestAPI("http://example.com/wp-json/wc/v3/", "ck_xxxx", "cs_xxxxxxx");
            WCObject wc = new WCObject(rest);
            var products = await wc.Product.GetAll();
            var p = await wc.Product.GetAll(new Dictionary<string, string>() {
                       {"tag", Suppliers.tagid },
                    { "per_page", "80" } }); ;

                productsListView.ItemsSource = p;

        }
mm8

The ItemsSource can only set to an IEnumerable, i.e. you have to create a collection of products:

productsListView.ItemsSource = new Product[1] { p };

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

CS0266 cannot implicitly convert type 'System.Collections.Generic.IEnumerable<char>' to 'string'

Ошибка состояния подавления CS0266 Невозможно неявно преобразовать тип '' в 'System.Collections.IEnumerable'

Cannot implicitly convert anonymous type to System.Collections.Generic.List

Cannot implicitly convert type 'System.Collections.Generic.List in asp.net MVC

Cannot convert from 'System.Collections.IList' to 'System.Collections.Generic.IEnumerable<T>'

Cannot implicitly convert type 'bool' to 'System.DateTimeOffset?'

CS0266 - Невозможно неявно преобразовать тип "System IList" в "System ArrayList" - Тестирование программного обеспечения

Cannot implicitly convert type 'bool' to 'int'

Cannot implicitly convert type 'System.Threading.Tasks.Task<object>' to 'string' in SignalR

Cannot implicitly convert type 'Program.Data.View' TO System.linq.iqueryable<Program.Data.View>.

Cannot implicitly convert type 'System.Numerics.BigInteger' to 'int'. An explicit conversion exists (are you missing a cast?)

Невозможно реализовать тип с инициализатором коллекции, поскольку он не реализует System.Collections.IEnumerable

Cannot convert type IEnumerable to List C#

How to declare variable of the type System.Collections.Generic.IEnumerable?

Powershell Hashtable: Cannot convert value "System.Collections.Hashtable" to type "Microsoft.PowerShell.Cmdletization.GeneratedTypes"

How do I debug "cannot convert to system.collections.generic.list" error

Cannot implicitly convert type Windows.Devices.Enumeration.DeviceWatcher to DeviceWatcher

list.AddRange Cannot implicitly convert type 'void'

Cannot implicitly Convert Type (C# and Visual Studio)

Issue with array (Cannot implicitly Convert Type 'int' to 'int[]')

Cannot implicitly convert type when using generics with constraints

'System.Collections.Generic.List`1 [<> f__AnonymousType1, но для этого словаря требуется элемент модели типа' System.Collections.Generic.IEnumerable ERROR

LINQ для System.Collections.IEnumerable

Невозможно инициализировать тип PeopleModel с помощью инициализатора коллекции, поскольку он не реализует System.Collections.IEnumerable

System.Collections.Generic.IEnumerable не содержит определения ошибки

для этого словаря требуется элемент модели типа System.Collections.Generic.IEnumerable

system.collections.generic.IEnumerable Ошибка

Cannot implicitly convert string to bool

CS0266 не может преобразовать тип

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    Машинопись: перебор каждого члена между двумя классами и разность флагов в Angular

  3. 3

    Как разбить строку на несколько строк и сохранить пробелы в YAML?

  4. 4

    Проверьте, была ли новая вкладка открыта с помощью puppeteer

  5. 5

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  6. 6

    Элемент "эллипс", созданный с помощью JS, не отображается в HTML

  7. 7

    How do I search for an entry out of two SQL tables and know which table it came from?

  8. 8

    Сделать программу автоматически добавлять текстовые поля в java

  9. 9

    JavaFX TextArea как установить текст с автоматическим переносом новой строки

  10. 10

    Как я могу нарисовать заполненный прямоугольник в JFreeChart?

  11. 11

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  12. 12

    Merging legends in plotly subplot

  13. 13

    ViewPager2 мигает / перезагружается при смахивании

  14. 14

    что делать, если в коде нет объявления Tk ()

  15. 15

    YAML: ошибка при разборе строки, содержащей квадратную скобку в качестве первого символа

  16. 16

    Передача параметра msbuild в Build.proj

  17. 17

    Как фильтровать таблицу SQLite3 в PyQt5

  18. 18

    Как в точности работает внутренний пул потоков Nodejs?

  19. 19

    Нарушение ограничения внешнего ключа JPA не может вставить Null

  20. 20

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  21. 21

    Невозможно запустить iReports 5.6.0 с Netbeans 8 и JDK 1.8

популярныйтег

файл