首页 > 解决方案 > DataTemplate 未正确绑定

问题描述

我正在尝试将MessageModel'sauthormessageproperties 绑定到 DataTemplate MessageTemplate。但是,我收到 BindingExpression 路径错误:

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')

这是我在 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;
        }
    }

这是我的 xaml 代码:

    <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>

我应该用什么来代替{Binding Path=}它才能工作?

标签: c#wpfdata-binding

解决方案


推荐阅读