0

Just when I think I've got a handle on WPF/XAML and view model binding I hit a snag. Here's a streamlined example of an issue I'm having:

Consider the following classes:

namespace TestApp
{
    public class BandMember
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    public class Band
    {
        public BandMember[] member = new BandMember[4];

        public Band()
        {
            for (int i= 0; i < 4; i++)
            { member[i] = new BandMember(); }
        }
    }

    public class Modify
    {
        public static Band SetBandMembers()
        {
            Band b = new();

            b.member[0].FirstName = "John";
            b.member[0].LastName = "Lennon";
            b.member[1].FirstName = "Paul";
            b.member[1].LastName = "McCartney";
            b.member[2].FirstName = "Ringo";
            b.member[2].LastName = "Starr";
            b.member[3].FirstName = "George";
            b.member[3].LastName = "Harrison";
            return b;
        }
    } 
}

In the View Model I have

namespace TestApp
{
    class ViewModel
    {
        public Band Beatles { get; set; }

        public string Test { get; set; }
        public ViewModel()
        {
            Beatles = new();
            Beatles = Modify.SetBandMembers();
            Test = "This is the test";
        }
    }
}

And in the XAML:

   <TextBlock Text="{Binding Beatles.member[3].LastName}"
               Grid.Row="0"
               Width="200" Height="60"/>
    <TextBlock Text="{Binding Test}"
               Grid.Row="0"
               Width="200" Height="60"/>

I know the view model binding is correct, as the {Binding Test} text block displays correctly. But trying to bind to Beatles fails, the text block is blank.

I tried the exact same thing in a console app, with the same classes and calling the same code found in the view model constructor, and was able to write ln the Beatles members' values.

The error I get in VS says when I look at the debugging trace says:

Error: 40 : BindingExpression path error: 'member' property not found on 'object' ''Band' (HashCode=30265903)'. BindingExpression:Path=Beatles.member[3].LastName; DataItem='ViewModel'

Sebastian Inones
  • 1,561
  • 1
  • 19
  • 32
  • You didn't share the part of the code where you assign the DataContext property. – Qwertyluk Jul 02 '21 at 22:34
  • 1
    The error message _"'member' property not found on 'object' ''Band'"_ says it all. There is no `member` **property**. Just a field. See duplicate. – Peter Duniho Jul 02 '21 at 23:09

0 Answers0