WPF Datagrid绑定不显示值 [英] WPF Datagrid binding does not show values

查看:342
本文介绍了WPF Datagrid绑定不显示值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WPF的初学者,我尝试在WPF中绑定到数据网格

I am total begginer with WPF and I try to make binding to datagrid in WPF

这里是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类

Here is MailTpl class

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

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

I don't know why it does not work. Any clues? Grid shows no values.

推荐答案

只是对未来的建议。

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

Visual studio -> Options -> Debugging -> Output Window -> WPF Trace Settings. Here you can set the level of verbosity and see important information about data binding in Ouptut window. It saved me hours.

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

Now the reson. You declared MailCollection as public property of the Window but binding is made against DataContext by default.

因此,您有两种方法:

this.DataContext = _MailCollection

,然后将绑定更改为

ItemsSource={Binding}

或只是更改对此的绑定:

or just change binding to this:

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

I还推荐此 pdf装订备忘单。它缺少一些WPF 4.5功能,但仍然有用。

I also recommend this pdf binding cheat sheet. It lacks some WPF 4.5 features but still useful.

这篇关于WPF Datagrid绑定不显示值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆