一下是前端和后端的代码:
<Grid>
<DataGrid Name="FileDataGrid" AutoGenerateColumns="False" Height="150" CanUserAddRows = "false">
<DataGrid.Columns>
<DataGridTemplateColumn Header="姓名" Width="200*" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Name="labName" Text="{Binding Name}" Width="200" Height="25" VerticalAlignment="Center" TextAlignment="Left" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="年龄" Width="200*" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Name="labAge" Text="{Binding Age}" Width="200" Height="25" VerticalAlignment="Center" TextAlignment="Left" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
public void MyWindow_25_Loaded(object sender, RoutedEventArgs e)
{
List<Person> person = new List<Person>()
{
new Person(){ Id="1",Name="Jack",Age="20"},
new Person(){Id="2",Name="Alan",Age="23"}
};
this.FileDataGrid.ItemsSource = person;
try
{
int index = FileDataGrid.CurrentCell.Column.DisplayIndex;
DataGridTemplateColumn templeColumn = FileDataGrid.Columns[index] as DataGridTemplateColumn;
if (templeColumn == null) return;
object item = FileDataGrid.CurrentCell.Item;
FrameworkElement element = templeColumn.GetCellContent(item);
TextBlock expander = templeColumn.CellTemplate.FindName("labAge", element) as TextBlock;
}
catch (Exception ex)
{
throw ex;
}
}
现在有这样的一个需求,当页面加载完了之后,在年龄这一列,当年龄小于20岁,将这一列的背景色设为蓝色,当年龄大于30岁,将这一列的背景色设为红色,上面的代码中,try模块中就是要获取年龄这个控件,但是:int index = FileDataGrid.CurrentCell.Column.DisplayIndex;走到这里就抛出了未将对象引用设置到对象的实例,请问各位大神,还有没有好的办法,来实现这一需求呢?
你又没有focus cell,CurrentCell.Column当然是null,可以写一个类似下面的Converter:
[ValueConversion(typeof(int), typeof(Brush))] public class MyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { int i = (int)(value); if (i <= 20) return Brushes.Blue; else if (i >= 30) return Brushes.Red; else return Brushes.White; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
英雄所见略同,后来我也是用Converter来转换的,最开始想的就是在列表加载完了,然后就开始对列表里的某一个控件进行操作,最后发现不行,Converter是个不错的方法