我是 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/