Skip to main content
 首页 » 编程设计

c#之如何将数据表设置为 WPF 数据网格 C#

2024年04月12日11daizhj

我是 C# 新手,所以放轻松。

基本上,我构建了一个数据表(并且我已经验证它不为空),但它似乎没有显示在我的 wpf 数据网格中...我在这里使用了这个示例并应用了它:link text

我的数据网格仍然空白。

你们觉得这个例子合适吗?

这是我的代码:

XACML:

<Window x:Class="WpfApplication1.TickerSearch" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="TickerSearch" Height="468" Width="907"> 
<Grid Background="#E6000000" Name="_grid"> 
    <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="244*" /> 
        <ColumnDefinition Width="37*" /> 
    </Grid.ColumnDefinitions> 
    <TextBox Height="34" HorizontalAlignment="Left" Margin="26,15,0,0" Name="txtSearchTker" VerticalAlignment="Top" Width="225" Grid.ColumnSpan="2" /> 
    <Button Content="Search" Height="32" HorizontalAlignment="Left" Margin="76,160,0,0" Name="btnSearch" VerticalAlignment="Top" Width="124" Click="btnSearch_Click" /> 
    <ListBox Height="114" HorizontalAlignment="Left" Margin="26,224,0,0" Name="lstResults" VerticalAlignment="Top" Width="225" Visibility="Hidden" Grid.ColumnSpan="2" Background="#FFFFB000" /> 
    <Button Content="Select" Height="32" HorizontalAlignment="Left" Margin="76,366,0,0" Name="btnSelect" VerticalAlignment="Top" Width="124" Visibility="Hidden" /> 
    <Label Content="Start Date: " Height="25" HorizontalAlignment="Left" Margin="22,65,0,0" Name="label1" VerticalAlignment="Top" Width="71" Background="#00FFB000" FontFamily="Georgia" Foreground="#FFFFB000" /> 
    <Label Content="End Date:" Height="27" HorizontalAlignment="Left" Margin="22,93,0,0" Name="label2" VerticalAlignment="Top" Width="71" Background="#00FFB000" FontFamily="Georgia" Foreground="#FFFFB000" /> 
    <DatePicker Height="22" HorizontalAlignment="Left" Margin="93,65,0,0" Name="dateFrom" VerticalAlignment="Top" Width="138" /> 
    <DatePicker Height="22" HorizontalAlignment="Left" Margin="93,94,0,0" Name="toDate" VerticalAlignment="Top" Width="138" /> 
    <Label Content="Just Today" Height="27" HorizontalAlignment="Left" Margin="22,122,0,0" Name="label3" VerticalAlignment="Top" Width="71" Background="#00FFB000" FontFamily="Georgia" Foreground="#FFFFB000" /> 
    <CheckBox Content="CheckBox" Height="17" HorizontalAlignment="Left" Margin="93,127,0,0" Name="chkBoxToday" VerticalAlignment="Top" Width="15" /> 
    <DataGrid AutoGenerateColumns="False" Height="315" HorizontalAlignment="Left" Margin="285,68,0,0" x:Name="_dataGrid" VerticalAlignment="Top" Width="468" ItemsSource="{Binding Path=.}" Background="#C6F7F700"></DataGrid> 
</Grid> 

c#:

            _ds = new DataSet(); 
            DataTable table = yahooFinance.lookupSymbol(); 
            _ds.Tables.Add(table); 
            _grid.DataContext = _ds.Tables[0]; 

请您参考如下方法:

将其更改为ItemsSource="{Binding}"

此外,将 AutoGenerateColumns 设置为 true。 (或明确指定列)