Associating ListBox with Interface Properties in Silverlight

I'm having problems binding data binding to a ListBox. I suspect this because I'm trying to bind data to an interface, not a class.

My C # code:

namespace MyNamespace
{
    interface IFoo
    {
        string Bar { get; }
    }

    class Fizz
    {
        private class Buzz : IFoo
        {
            public string Bar { get { return "something"; } }
        }

        public IEnumerable<IFoo> GetFoo()
        {
            List<Buzz> items = new List<Buzz>();
            // Populate items
            return items;
        }
    }
}

When I try to bind data to pins from Fizz::GetFoo(), this will not work. My XAML looks like this:

<ListBox Name="listBox1" ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                 <TextBlock Text="Bar:" />
                 <TextBlock Text="{Binding Bar}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

When I run it, I see text for the first TextBlock, but not the second. I see errors in the output window similar to this:

    System.Windows.Data Error: Cannot get 'Bar' value (type 'System.String') from 'Buzz' (type 'MyNamespace.Fizz+Buzz'). BindingExpression: Path='Bar' DataItem='Buzz' (HashCode=100433959); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String').. System.MethodAccessException: Attempt to access the method failed: MyNamespace.Fizz+Buzz.get_Bar()
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
   at System.Reflection.RuntimePropertyInfo.InternalGetValue(PropertyInfo thisProperty, Object obj, Object[] index, StacA first chance exception of type 'System.MethodAccessException' occurred in mscorlib.dll

- ?

+3
2

, ( List List<IFoo> List<Bar>):

public interface IFoo
{
    string Bar { get; }
}

public class Fizz
{
    public class Buzz : IFoo
    {
        public string Bar { get { return "something"; } }
    }

    public IEnumerable<IFoo> GetFoo()
    {
        List<IFoo> items = new List<IFoo>();
        // Populate items
        return items;
    }
}

, , . Silverlight ( internal, ). Buzz , , , .

, , . IFoo, Buzz . , , , .

+4

, Buzz , .

+1

Source: https://habr.com/ru/post/1795716/


All Articles