c# - WPF DataGrid 绑定(bind)不显示值

标签 c# .net wpf data-binding expression-blend

我是 WPF 的初学者,我尝试在 WPF 中绑定(bind)到 DataGrid。

XAML 代码:

<Grid x:Name="LayoutRoot">
    <Grid HorizontalAlignment="Left" Height="440" VerticalAlignment="Top"
        Width="632">
        <DataGrid HorizontalAlignment="Left" Height="420" Margin="10,10,0,0"
            VerticalAlignment="Top" Width="603" ItemsSource="{Binding
            Source=MailCollection}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn  Header="id" Binding="{Binding Id}"/>
                <DataGridTextColumn  Header="nazwa" Binding="{Binding Name}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Grid>

这是 MailTpl 类:

public class MailTpl
{
    public string Id { get; set; }
    public string Name { get; set; }
}

下面是我如何进行绑定(bind):

public partial class WindowDataGridTest : Window
{
    ObservableCollection<MailTpl> _MailCollection =
        new ObservableCollection<MailTpl>();
    public ObservableCollection<MailTpl> MailCollection
        { get { return _MailCollection; } }

    public WindowDataGridTest()
    {
        _MailCollection.Add(new MailTpl
            { Id= "abbb", Name = "badfasdf" });
        _MailCollection.Add(new MailTpl
            { Id = "asasdfasdfdf", Name = "basdfasdfaa" });
        this.InitializeComponent();
        // Insert code required on object creation below this point.
    }
}

我不知道为什么它不起作用。有什么线索吗?网格不显示任何值。

最佳答案

只是对 future 的建议。

Visual studio -> 选项 -> 调试 -> 输出窗口 -> WPF Trace设置。 您可以在此处设置详细级别,并在 Output 窗口中查看有关数据绑定(bind)的重要信息。它为我节省了数小时。

现在是原因。 您将 MailCollection 声明为 Window 的公共(public)属性,但默认情况下是针对 DataContext 进行绑定(bind)的。

所以,你有两种方法:

this.DataContext = _MailCollection

并将绑定(bind)稍微更改为:

ItemsSource={Binding}

或者只是更改对此的绑定(bind):

ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
              AncestorType=Window}, Path=MailCollection}"

我也推荐这个PDF binding cheat sheet .它缺少一些 WPF 4.5 功能,但仍然有用。

关于c# - WPF DataGrid 绑定(bind)不显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15761124/

相关文章:

c# - 如何将海量数据离线存储,然后批量更新到SQLite数据库中?

wpf - 如何在 WPF 中隐藏组合框的项目

非焦点形式的 C#/WPF 热键(如 launchy)

c# - 通过使用任务加快处理改进

c# - 嵌套对象上的Elasticsearch过滤器范围

c# - 当非虚拟化 DataGrid 中有大量行时,WPF 应用程序 DataGrid 控制窗口切换滞后

c# - 如何使用 OpenXML SDK 2.5 从 word 文档中复制公式?

c# - 尝试从我的网络应用程序签署可下载的 exe 文件的安全问题

c# - 从网站批量打印存储在服务器上的文件

C# 将列表与自定义对象进行比较但忽略顺序