【问题标题】:XAML: Simple ItemsControl Binding to TextBox does not work: how to set the source property?XAML:简单的 ItemsControl 绑定到 TextBox 不起作用:如何设置源属性?
【发布时间】:2017-04-08 03:40:04
【问题描述】:

我有一个 ObservableCollection,我尝试将它绑定到一个文本框列表。文本框会显示,但文本内容不会。

XAML:

<Grid>
    <Grid.RowDefinitions >
        <RowDefinition />
    </Grid.RowDefinitions>
    <ItemsControl ItemsSource="{Binding Path=ListOfMessages}" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Path=Message, ElementName=ListOfMessages}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

守则:

在 ViewModel 中:

public ObservableCollection<ApplicationLog> ListOfMessages { get; set; }

在模型中:

public class ApplicationLog 
{
    public string Code { get; set; }
    public string Message { get; set; }
}

当我运行它时,应用程序会显示文本框(例如 4 个文本框,一个在另一个下方),但文本框中的文本(即Message 属性)未显示。我认为我对文本框的绑定表达式是错误的。

上下文:我是 XAML 和 WPF 的新手。更一般地说:如何调试与此类似的绑定问题。

谢谢。

【问题讨论】:

  • 如果您在调试时查看输出窗口,您应该会看到 Binding 错误提示。
  • 谢谢。但我很难阅读:System.Windows.Data 错误:4:找不到与引用“ElementName = ListOfMessages”进行绑定的源。绑定表达式:路径=消息;数据项=空;目标元素是'TextBox'(名称='');目标属性是“文本”(类型“字符串”)这告诉我绑定不起作用 - 我还能推断出什么?
  • 这告诉您数据上下文正在尝试绑定到 ListOfMessages.Message。 ObservableCollection 没有“消息”的属性......正如您在答案中看到的那样。任何列表项的数据上下文都是集合的项。很高兴你解决了。

标签: c# wpf xaml binding itemscontrol


【解决方案1】:

删除ElementName=ListOfMessages。每个项目的DataContext 将是绑定到ItemsSourceListOfMessages 中的项目。

<Grid>
    <Grid.RowDefinitions >
        <RowDefinition />
    </Grid.RowDefinitions>
    <ItemsControl ItemsSource="{Binding Path=ListOfMessages}" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <!-- DataContext will be ListOfMessages[0], [1], ..., [n] -->
                <TextBox Text="{Binding Path=Message}" /> 
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

ElementName 用于绕过DataContext 并指向作用域 XAML 中的特定命名项。

【讨论】:

  • 谢谢;做到了! Intellisense 在 XAML 中用“无法解析符号'消息'”提示“无法解析符号'消息'”(在 VS2017 中)下划线(蓝色)“消息”让我感到惊讶;所以我什至没有尝试过。为什么 Intellisense 会给我这个信息?
  • Intellisense 不知道 ListOfMessages 的来源。您需要在 xaml 中的根元素上使用 d:DataContext。看看这个帖子,例如stackoverflow.com/questions/15101696/…
猜你喜欢
  • 2015-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 2016-07-27
  • 2015-09-25
  • 1970-01-01
  • 2011-07-19
相关资源
最近更新 更多