0

I am trying to bind MessageModel's author and message properties to the DataTemplate MessageTemplate. However, I get a BindingExpression path error:

System.Windows.Data Error: 40 : BindingExpression path error: 'message' property not found on 'object' ''MessageModel' (HashCode=3048957)'. BindingExpression:Path=message; DataItem='MessageModel' (HashCode=3048957); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')

This is my code inside MainWindow:

    List<MessageModel> messageList;
    public MainWindow()
    {
        InitializeComponent();

        messageList = new List<MessageModel>()
        {
            new MessageModel("Test1", "Message 1"),
            new MessageModel("Test1", "Message 2"),
            new MessageModel("Test2", "Message 3"),
            new MessageModel("Test2", "Message 4")
        };

        this.messageListBox.ItemsSource = messageList;
    }

    class MessageModel
    {
        public string author;
        public string message;

        public MessageModel(string _author, string _message)
        {
            author = _author;
            message = _message;
        }
    }

And here is my xaml code:

    <Grid>
        <ListBox x:Name="messageListBox" ItemTemplate="{DynamicResource MessageTemplate}" Margin="0,133,0,0">
            <ListBox.Resources>
                <DataTemplate x:Key="MessageTemplate">
                    <Grid Margin="0,0,0,0">
                        <Label Content="{Binding Path=author}" HorizontalAlignment="Left" Height="31" VerticalAlignment="Top" Width="63"/>
                        <Label Content="{Binding Path=message}" HorizontalAlignment="Left" Height="31" Margin="0,31,0,0" VerticalAlignment="Top" Width="790"/>
                    </Grid>
                </DataTemplate>
            </ListBox.Resources>
        </ListBox>
    </Grid>

What should I replace the {Binding Path=} with for this to work?

  • 1
    `public string message;` is a field, not a property. Data binding only works with properties. As a note, instead of a Label, better bind the Text property of a TextBlock. – Clemens Sep 21 '20 at 17:33
  • As another note, instead of assigning the ItemTemplate to a resource in ListBox.Resources, it seems simpler to set it directly by `...` – Clemens Sep 21 '20 at 17:38
  • Thanks it works. Why is a TextBlock recommended over a Label? – wfqlhfsdljvbjhdsf.ajdf Sep 21 '20 at 20:31
  • It's simpler, designed to show text only. A Label can also display other, more complex content. – Clemens Sep 21 '20 at 20:36

0 Answers0