2013-04-02 72 views
1

我与WPF总初学者,我要尽量作出有约束力的WPFWPF Datagrid的约束力不显示值

这里的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. 
    } 
} 

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

回答

14

只是对未来的建议。

Visual Studio - >选项 - >调试 - >输出窗口 - > WPF跟踪设置。 在这里,您可以设置详细程度并在Ouptut窗口中查看有关数据绑定的重要信息。它节省了我几个小时。

现在共振。 您将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功能,但仍然有用。

+0

谢谢你的工作。我将更多地阅读它。 – Robert

+0

感谢“Trace WPF”提示,它帮助我了解了我的问题! – MSE

1

您已经忘记在WindowDataGridTest()构造函数中编写它。

this.DataContext = this; 
+1

谢谢。我正在跟随教程,并没有在那里提到。 – Robert

1

你有没有势必的的ObservableCollection到DataGrid。

以下是实现您的问题的步骤。

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

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

    myDataGrid.DataContext = this.MailCollection; 
    

并请看看this tutorial更多地了解数据绑定

+0

好的。我会感谢你的时间。正如我所提到的,我开始使用WPF,所以即使简单的事情也不容易:) – Robert

+0

作为WPF的新手,我建议您在应用程序中应用MVVM。并了解INotifyPropertyChanged,DataBinding ... – Haritha

+0

我已经阅读了一些关于它,但我会阅读更多。 – Robert

0

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