WPF不显示datagrid中的数据

时间:2013-04-08 18:37:47

标签: c# wpf xaml

我正在关注一些示例,我无法在数据网格中显示数据。值得一提的是,我在查看debuger时从db获取数据。

MainWindow.xaml.cs

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

    }

public partial class MainWindow : Window
{
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        using (session...)
        {
            using (transaction...)
            {
                var properties = new List<MyProperty>();
                // this variable is populated inside debugger
                properties = session.Query<MyProperty>().ToList();
                if (properties != null)
                {
                    MRDataGrid.Columns[0].Visibility = System.Windows.Visibility.Hidden;
                    MRDataGrid.Columns[1].Visibility = System.Windows.Visibility.Hidden;
                    MRDataGrid.Columns[8].Visibility = System.Windows.Visibility.Hidden;
                }
            }
        }
    }
}

MainWindow.xaml

<Window x:Class="MyProject.WPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        WindowStartupLocation="CenterScreen" BorderBrush="Black"
        Background="AntiqueWhite" ResizeMode="NoResize"
        Loaded="Window_Loaded">
    <Grid>
        <DataGrid AutoGenerateColumns="False" Height="202" HorizontalAlignment="Left" Margin="22,82,0,0" 
                  Name="MRDataGrid" VerticalAlignment="Top" Width="461" ItemsSource="{Binding}"/>
    </Grid>
</Window>

更新

  • 我在MainWindow.xaml中更改为AutoGenerateColumns =“True”
  • 添加了MRDataGrid.ItemsSource = properties;在xaml.cs代码中
  • 我应该在MainWindow.xaml中的ItemSource中放置什么?

3 个答案:

答案 0 :(得分:1)

您没有为ItemsSource="{Binding}"设置任何上下文。

执行myDataGrid.DataContext=...之类的操作或绑定数据上下文或将{Binding}更改为您需要的位置

如:

if (properties != null)
 {
    myDataGrid.ItemsSource = properties;
    ...

答案 1 :(得分:0)

properties = session.Query()。ToList();

MRDataGrid.ItemsSource = properties;

答案 2 :(得分:0)

您的数据网格没有列。您需要自己声明或设置AutoGenerateColumns="True"您还需要像Sten Petrov那样指定项目来源