Silverlight中MVVM,为DataGrid绑定每一行的提示信息。
网上找的都是绑定头部或者“单元格”的,现在尝试了又尝试后,发现绑定行可以这样绑定:
<sdk:DataGrid x:Name="batchGrid" AutoGenerateColumns="False" LoadingRow="batchGrid_LoadingRow_1" ItemsSource="{Binding BatchViewList,Mode=TwoWay}" SelectedItem="{Binding CurrentBatch,Mode=TwoWay}" > <sdk:DataGrid.RowStyle> <Style TargetType="sdk:DataGridRow"> <Setter Property="ToolTipService.ToolTip" Value="{Binding DisplayOpinion}"/> </Style> </sdk:DataGrid.RowStyle> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Header="编号" Binding="{Binding BatchNO}" IsReadOnly="True" /> <sdk:DataGridTextColumn Header="项目" Binding="{Binding DisplayName}" IsReadOnly="True" /> <sdk:DataGridTextColumn Header="时间" Binding="{Binding BatchDate,StringFormat=yyyy年MM月dd日}" IsReadOnly="True" /> </sdk:DataGrid.Columns>
</sdk:DataGrid>
另外,试图MVVM绑定行的背景色失败,只好在Behind Code里面做了,参考了别人的写法,在LoadingRow事件中处理。
private void batchGrid_LoadingRow_1(object sender, DataGridRowEventArgs e) { //获取当前加载的行标(从0开始) int i = e.Row.GetIndex(); //获取DataGrid绑定的数据。 var list = batchGrid.ItemsSource as List<AnalysisBatchView>; if (list != null) { //遍历数据行,进行颜色设置 int j = 0; foreach (AnalysisBatchView model in list) { //设置背景颜色,这里可以判断行,需要进行设置的行,设置颜色 if (model.IsRockback && j == i) { e.Row.Background = new SolidColorBrush(Colors.Red); } j++; } } }