c# - DataTemplate 未正确绑定
问题描述
我正在尝试将MessageModel
'sauthor
和message
properties 绑定到 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++ - 我用 C++ 编写了一个程序,通过空格键将单词从一行中分离出来,并将这些单词显示为一个数组。我的代码有什么问题?
- rust - 如何在 Rust 中将两个 i16 相加或相乘以形成一个 i32 而不会溢出?
- botframework - 通过 api 向微软团队中的机器人用户发送消息
- php - 是否可以为我从数据库输出的数据分配一个“名称”?
- javascript - 调整 div 大小时无法让 Google 地图高度自动调整大小
- nginx - 您的连接不是私有的(nginx、bluehost、google cloud 和 cloudflare)
- javascript - 如何进行可重用的 proptype 验证?
- python - 如何使用字符串(或其他类型的元数据)中的逻辑向(PySpark)数据框添加新列?
- javascript - 对如何在 JS 中使用变量感到困惑
- android - 如何在我的代码中插入 CALLBACK 代码