【问题标题】:WPF DataGrid binding does not show valuesWPF DataGrid 绑定不显示值
【发布时间】:2013-03-23 13:42:20
【问题描述】:

我是 WPF 的初学者,我尝试在 WPF 中绑定到 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; }
}

以下是我的绑定方式:

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

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

【问题讨论】:

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


    【解决方案1】:

    只是对未来的建议。

    Visual studio -> Options -> Debugging -> Output Window -> WPF Trace Settings。 您可以在此处设置详细级别并在Output 窗口中查看有关数据绑定的重要信息。它为我节省了几个小时。

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

    所以,你有两种方法:

    this.DataContext = _MailCollection
    

    并将绑定更改为:

    ItemsSource={Binding}
    

    或者只是将绑定更改为:

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

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

    【讨论】:

    • 感谢“Trace WPF”提示,它也帮助我理解了我的问题!
    【解决方案2】:

    我遇到了同样的问题,然后我通过增加网格高度来解决它。 确保您的 Grid 高度足以显示数据。

    【讨论】:

      【解决方案3】:

      没有将 ObservableCollection 绑定到 DataGrid。

      这是解决问题的步骤。

      1. 为您的 DataGrid 定义一个名称。 (比如说myDataGrid

      2. 然后在代码隐藏文件的构造函数中插入下面的代码

        myDataGrid.DataContext = this.MailCollection;
        

      请查看this tutorial 以了解有关数据绑定的更多信息

      【讨论】:

      • 好的。我会感谢你的时间。正如我所提到的,我开始使用 WPF,所以即使是简单的事情也不容易 :)
      • 作为 WPF 的新手,我建议你在你的应用程序中应用 MVVM。并了解 INotifyPropertyChanged、DataBinding...
      【解决方案4】:

      你忘记在 WindowDataGridTest() 构造函数中写这个了。

      this.DataContext = this;
      

      【讨论】:

      • 谢谢。我正在关注教程,但那里没有提到。
      猜你喜欢
      • 1970-01-01
      • 2014-02-09
      • 2011-04-19
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      相关资源
      最近更新 更多