急,急,急。数据为什么没能绑定上呢?
急,急,急。数据为什么没能绑定上呢?
1、后台代码:
namespace SLCustomGridHeader
{
public partial class CustomReport : UserControl
{
public CustomReport()
{
// 为初始化变量所必需
InitializeComponent();
}
}
public class EnergyList
{
private string _energytitle;
public string EnergyTitle
{
get {return _energytitle;}
set { _energytitle = "能耗指标报表 (单位,MJ)"; }
}
问题一:如下直接在“EnergyList”类中定义成员变量“energylist”,它可以被绑定吗???
public List<EnergyTarget> energylist = new List<EnergyTarget> {
new EnergyTarget{EnergyYear="2010",EnergySum="7678.09",EnergyEveryOne="89.78",EnergyUnitArea="45.65"},
new EnergyTarget{EnergyYear="2011",EnergySum="8978.48",EnergyEveryOne="67.75",EnergyUnitArea="43.63"}
};
}
public class EnergyTarget
{
public string EnergyYear
{
get;
set;
}
public string EnergySum
{
get;
set;
}
public string EnergyUnitArea
{
get;
set;
}
public string EnergyEveryOne
{
get;
set;
}
}
}
2、前台XAML:
<Grid x:Name="LayoutRoot">
<Grid Margin="69,80,79,82">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.DataContext>
<local:EnergyList/>
</Grid.DataContext>
<sdk:Label Background="#FFB7D4E0" Content="{Binding EnergyTitle}"/>
问题二:“Grid”中已经定义了数据上下文,为什么没能绑定数据到“Lable”???
<sdk:DataGrid Grid.Row="1" ItemsSource="{Binding energylist}">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn CanUserSort="True" CanUserReorder="True" CellStyle="{x:Null}" CanUserResize="True" CellEditingTemplate="{x:Null}" ClipboardContentBinding="{x:Null}" DisplayIndex="-1" DragIndicatorStyle="{x:Null}" HeaderStyle="{x:Null}" Header="年份" IsReadOnly="True" MaxWidth="Infinity" MinWidth="0" SortMemberPath="{x:Null}" Visibility="Visible" Width="Auto">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontSize="13" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding EnergyYear}"></TextBlock>
问题三:DataGrid已经指定了“ItemsSource”属性,为什么“TextBlock”没能绑定指定的属性???
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</Grid>
</Grid>
3、数据没能绑定,截图如下:
[img=http://social.msdn.microsoft.com/Forums/getfile/142739][/img]
[解决办法]
你这类中的字段都没有指定DataGrid的列吧,,列上面也要指定帮顶的字段啊,比如
<sdk:DataGridTextColumn Binding="{Binding EnergyYear}" Width="*" Header="年份" />
[解决办法]
可以后台指定,DataGrid的ItemSource=energylist
[解决办法]
private List<EnergyTarget> energyList;
public List<EnergyTarget> EnergyList
{
get
{
if(energyList == null)
energyList = new List<EnergyTarget> {
new EnergyTarget {EnergyYear="2010",EnergySum="7678.09",EnergyEveryOne="89.78",EnergyUnitArea="45.65"},
new EnergyTarget{EnergyYear="2011",EnergySum="8978.48",EnergyEveryOne="67.75",EnergyUnitArea="43.63"}
};
return energyList;
}
}