代码改变世界

silverlight系列(DataBinding、DataGrid)

2010-03-05 11:02  key_sky  阅读(3829)  评论(1编辑  收藏  举报

一、数据绑定类型

  • OneTime绑定:一次绑定,该绑定使用源数据更新目标。
  • OneWay绑定:每当源数据发生变化,该绑定使用源数据更新目标
  • TwoWay绑定:当目标和源有一个发生变化时,TwoWay绑定既更新目标也更新源。

为能够发生自动目标更新,源对象必须实现INotifyPropertyChanged接口。若要获取绑定到ItemControl的集合的更改通知,除了实现INotifyPropertyChanged外,还要实现INotifyCollectionChanged.如果实现INotifyCollectionChanged,对集合的更改将传播到目标。若要获取集合中对象的属性通知,对象必须实现INotifyPropertyChanged.

在TwoWay绑定中对从目标到源的更新进行基本数据验证。在发生以下情况时,Silverlight会报告验证错误:
  • 在绑定引擎的类型转换器中引发了异常。
  • 在绑定对象的set访问器中引发了异常。
  • 在应用到数据对象或成员的验证属性中引发了异常。
实现数据验证的步骤:
  • 将绑定对象的ValidatesOnExceptions设置为true,告知绑定引擎在发生异常时创建验证错误。
  • 将NotifyOnValidationError设置为true,告知绑定引擎在验证错误发生和解决时引发BindingValidationError事件。
  • 在目标对象或其任一父级上创建BindingValidationError一个事件处理程序,该事件为路由事件。

ObservableCollection()实现INotifyCollectionChanged,这意味着添加或删除列表项时将引发列表更改事件。这些列表更改将传播到绑定的控件。集合类型不实现INotifyPropertyChanged,表示该集合属性值的更改不会引发事件。属性更改不会传播到绑定的控件。

二、DataGrid详解

Properties:
  • AreRowDetailsFrozen:获取或设置行详细信息部分是在显示区域的宽度处保持固定,还是可以水平滚动
  • AreRowGroupHeadersFrozen:获取或设置行组标题部分在显示区域内保持固定的宽度,还是可以水平滚动
  • AutoGenerateColumns:获取或设置是否自动创建列
  • CanUserReorderColumns:用户是否可以拖动列
  • CanUserResizeColumnsL是否可以调整列宽
  • CanUserSortColumns:是否可单击列标题进行列排序
  • ColumnHeaderHeight:获取或设置列标题行的高度
  • FrozenColumnCount:获取或设置用户无法水平滚动的列数
  • GridLinesVisibility:获取或设置哪些分割内部单元格的网格线
  • HeadersVisibility:获取或设置行或列标题的可见性
  • IsReadOnly:获取或设置用户是否可以编辑控件中的值
  • SelectedIndex:获取或设置当前选择内容的索引
  • SelectedItems:获取包含与选定行对应的数据项的列表
  • SelectionMode:获取或设置数据网格的选择行为
Methods:
  • BeginEdit:设置当前单元格和当前行进入编辑模式
  • CancelEdit:取消当前编辑、恢复原始值并退出编辑模式。
  • OnAutoGeneratingColumn:引发AutoGeneratingColumn事件
  • OnBeginningEdit:引发BeginningEdit事件
  • OnCellEditEnded:引发CellEditEnded事件
  • OnCellEditEnding:引发CellEditEnding事件
  • OnColumnDisplayIndexChanged:引发ColumnDisplayIndexChanged事件
  • OnColumnReordered:引发ColumnReordered事件
  • OnColumnReordering:引发ColumnReordering事件
  • OnCurrentCellChanged:引发CurrentCellChanged事件
  • OnLoadingRow:引发LoadingRow事件
  • OnLoadingRowDetails:引发LoadingRowDetails事件
  • OnLoadingRowGroup:引发LoadingRowGroup事件
  • OnProperingCellForEdit:引发PreparingCellForEdit事件
  • OnRowDetailsVisibilityChanged:引发RowDetailsVisibilityChanged事件
  • OnRowEditEnded:引发RowEditEnded事件
  • OnRowEditEnding:引发RowEditEnding事件
  • OnSelectionChanged:引发SelectionChanged事件
  • SetBinding:设置提供的绑定对象
Events:
  • BeginningEdit:单元格或行进入编辑模式之前发生
  • CellEditEnded:提交或取消单元格编辑时发生
  • CellEditEnding:单元格编辑结束时发生
  • ColumnDisplayIndexChanged:在列的DisplayIndex属性更改时发生
  • ColumnHeaderDragCompleted:拖动列标题时发生
  • ColumnHeaderDragDelta:用户拖动列标题时发生一次或多次
  • ColumnHeaderDragStarted:开始拖动列标题时发生
  • ColumnReordered:列移至显示顺序中的新位置时发生
  • ColumnReordering:列移至显示顺序中的新位置之前发生
  • CurrentCellChanged:其他单元格成为单元格时发生
  • PreparingCellForEdit:当DataGridTemplateColumn中的单元格进入编辑模式时发生
  • RowDetailsVisibilityChanged:在RowDetailsVisibilityMode属性值更改时发生
  • RowEditEnded:提交或取消行编辑时发生
  • RowEditEnding:行编辑结束时发生
  • SelectionChanged:当SelectedItem或SelectedItems属性值更改时发生

DataBinding.xaml:

<Grid x:Name="LayoutRoot" VerticalAlignment="Top" HorizontalAlignment="Left"
BindingValidationError
="LayoutRoot_BindingValidationError">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Rectangle x:Name="myRec" Fill="{Binding Brush1, Mode=OneWay}" Grid.Row="0" Width="100"
Height
="45" MouseLeftButtonDown="myRec_MouseLeftButtonDown"/>
<TextBox x:Name="tbx2" Text="{Binding Data,Mode=TwoWay}" Grid.Row="1" Width="100" Height="25" />
</Grid>
<!--
数据绑定类型:
OneTime绑定:一次绑定,该绑定使用源数据更新目标。
OneWay绑定:每当源数据发生变化,该绑定使用源数据更新目标
TwoWay绑定:当目标和源有一个发生变化时,TwoWay绑定既更新目标也更新源。
为能够发生自动目标更新,源对象必须实现INotifyPropertyChanged接口。
若要获取绑定到ItemControl的集合的更改通知,除了实现INotifyPropertyChanged外,还要实现INotifyCollectionChanged
.如果实现INotifyCollectionChanged,对集合的更改将传播到目标。若要获取集合中对象的属性通知,对象必须实现
INotifyPropertyChanged.
在TwoWay绑定中对从目标到源的更新进行基本数据验证。在发生以下情况时,Silverlight会报告验证错误:
1.在绑定引擎的类型转换器中引发了异常。
2.在绑定对象的set访问器中引发了异常。
3.在应用到数据对象或成员的验证属性中引发了异常。
实现数据验证的步骤:
1.将绑定对象的ValidatesOnExceptions设置为true,告知绑定引擎在发生异常时创建验证错误。
2.将NotifyOnValidationError设置为true,告知绑定引擎在验证错误发生和解决时引发BindingValidationError事件。
3.在目标对象或其任一父级上创建BindingValidationError一个事件处理程序,该事件为路由事件。
-->

DataBinding.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Windows.Data;

namespace DataBinding1
{
public partial class MainPage : UserControl
{
TextData data;
MyColors textcolor;
List
<Color> listclolor = new List<Color>();
public MainPage()
{
InitializeComponent();

textcolor
= new MyColors();

textcolor.Brush1
= new SolidColorBrush(Colors.Green);

myRec.DataContext
= textcolor;
data
= new TextData { Data = 100 };
tbx2.DataContext
= data;

}
private void InitList()
{
listclolor.Clear();
listclolor.Add(Colors.Blue);
listclolor.Add(Colors.Brown);
listclolor.Add(Colors.Gray);
listclolor.Add(Colors.Green);
listclolor.Add(Colors.Magenta);
listclolor.Add(Colors.Orange);
listclolor.Add(Colors.Red);
listclolor.Add(Colors.Purple);
listclolor.Add(Colors.Yellow);
}
private void myRec_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
InitList();
List
<Color> listself = new List<Color>();
listself
= listclolor;
listself.Remove(((SolidColorBrush)myRec.Fill).Color);
Random random
= new Random();
int i = random.Next(0, listself.Count);
textcolor.Brush1
= new SolidColorBrush(listself[random.Next(0, listself.Count)]);
myRec.DataContext
= textcolor;
}

private void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e)
{

}


}
}

MyColors.cs:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace DataBinding1
{
public class MyColors : INotifyPropertyChanged
{
private SolidColorBrush _Brush1;

// Declare the PropertyChanged event.
public event PropertyChangedEventHandler PropertyChanged;

// Create the property that will be the source of the binding.
public SolidColorBrush Brush1
{
get { return _Brush1; }
set
{
_Brush1
= value;
// Call NotifyPropertyChanged when the source property
// is updated.
NotifyPropertyChanged("Brush1");
}
}


// NotifyPropertyChanged will raise the PropertyChanged event,
// passing the source property that is being updated.
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(
this,
new PropertyChangedEventArgs(propertyName));
}
}
}
}

TextData.cs:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace DataBinding1
{
public class TextData :INotifyPropertyChanged
{
private int _Data;
public event PropertyChangedEventHandler PropertyChanged;

public int Data
{
get { return _Data; }
set
{
_Data
= value;
if (PropertyChanged != null)
{
PropertyChanged(
this, new PropertyChangedEventArgs("Data"));
}
}
}


}
}

运行效果:

BindingToCollection.xaml:

<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" Width="Auto" Height="500"
ShowGridLines
="False" VerticalAlignment="Top" Margin="5,5,5,5">
<Grid.RowDefinitions>
<RowDefinition Height="150"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="155"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ListBox x:Name="lbx1" Margin="5,5,5,5" Width="300" Height="100" S
electionChanged
="lbx1_SelectionChanged" Grid.Row="0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="5" Height="20" />
<TextBlock Text="{Binding Old}" Margin="5" Height="20" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock x:Name="tb1" Width="500" Height="25" Foreground="Red" Grid.Row="1" ></TextBlock>
<TextBlock x:Name="tb2" Width="500" Height="25" Foreground="Red" Grid.Row="2" ></TextBlock>
<!--
ObservableCollection()实现INotifyCollectionChanged,这意味着添加或删除列表项时将引发列表更改事件。
这些列表更改将传播到绑定的控件。集合类型不实现INotifyPropertyChanged,表示该集合属性值的更改不会
引发事件。属性更改不会传播到绑定的控件。
-->
</Grid>

BindingToCollection.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Windows.Data;

namespace BindingToCollection
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
List
<Employees> employee = new List<Employees>();
employee.Add(
new Employees("keysky", 24, "安徽", "Like Programming,Reading,Football"));
employee.Add(
new Employees("cat", 26, "北京", "Like Testing,Dancing,Sports"));
employee.Add(
new Employees("wj", 32, "湖南", "Like Smoking,Managing,Sports"));
employee.Add(
new Employees("ds", 35, "湖南", "Like Reading,Managing,Sports"));
lbx1.ItemsSource
= employee;
BindBehind();
}

private void lbx1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Employees selemployee
= lbx1.SelectedItem as Employees;
tb1.Text
= "Name: " + selemployee.Name + " Old:" + selemployee.Old + " BirthPlace:" +
selemployee.BirthPlace
+ " SelfInfo:" + selemployee.Selfinfo;
}
/// <summary>
/// 后台数据绑定
/// </summary>
private void BindBehind()
{
Employees employee
= new Employees("keysky", 24, "安徽", "Like Programming,Reading,Football");
Binding bind
= new Binding();
bind.Path
= new PropertyPath("Name");
bind.Mode
= BindingMode.OneWay;
bind.Source
= employee;
tb2.DataContext
= employee;
tb2.SetBinding(TextBlock.TextProperty, bind);
}
}
}

Employees.cs:

public class Employees
{
public string Name { get; set; }
public int Old { get; set; }
public string BirthPlace { get; set; }
public string Selfinfo { get; set; }
public Employees(string name, int old, string birthplace, string selfinfo)
{
this.BirthPlace = birthplace;
this.Name = name;
this.Old = old;
this.Selfinfo = selfinfo;
}
}

运行效果:

DataGrid.xaml:

<Grid x:Name="LayoutRoot" VerticalAlignment="Top" HorizontalAlignment="Left">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="155"/>
<RowDefinition Height="35"/>
<RowDefinition Height="155"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<CheckBox x:Name="cbx1" Grid.Row="0" Background="AliceBlue" Content="编辑DataGrid"
Checked
="cbx1_Checked" Unchecked="cbx1_Checked" Margin="5"></CheckBox>
<data:DataGrid Width="500" Height="150" AutoGenerateColumns="False" Margin="5" x:Name="myGrid"
GridLinesVisibility
="All" IsReadOnly="True"
Grid.Row
="1" SelectionChanged="myGrid_SelectionChanged" HorizontalAlignment="Left">
<data:DataGrid.Columns>
<data:DataGridCheckBoxColumn Header="在职" Binding="{Binding Check}" DisplayIndex="0"/>
<data:DataGridTextColumn Header="姓名" Binding="{Binding Name}" />
<data:DataGridTextColumn Header="年龄" Binding="{Binding Old}"/>
<data:DataGridTextColumn Header="出生地" Binding="{Binding BirthPlace}"/>
</data:DataGrid.Columns>
<data:DataGrid.RowDetailsTemplate>
<DataTemplate>
<StackPanel Height="80" Background="LightPink" >
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Old}"/>
<TextBlock Text="{Binding BirthPlace}"/>
<TextBlock Text="{Binding Selfinfo}"/>
</StackPanel>
</DataTemplate>
</data:DataGrid.RowDetailsTemplate>
</data:DataGrid>
<TextBlock x:Name="tbinfo" FontSize="14" Height="25" Foreground="Green" Grid.Row="2" />
<!--
Properties:
AreRowDetailsFrozen:获取或设置行详细信息部分是在显示区域的宽度处保持固定,还是可以水平滚动
AreRowGroupHeadersFrozen:获取或设置行组标题部分在显示区域内保持固定的宽度,还是可以水平滚动
AutoGenerateColumns:获取或设置是否自动创建列
CanUserReorderColumns:用户是否可以拖动列
CanUserResizeColumnsL是否可以调整列宽
CanUserSortColumns:是否可单击列标题进行列排序
ColumnHeaderHeight:获取或设置列标题行的高度
FrozenColumnCount:获取或设置用户无法水平滚动的列数
GridLinesVisibility:获取或设置哪些分割内部单元格的网格线
HeadersVisibility:获取或设置行或列标题的可见性
IsReadOnly:获取或设置用户是否可以编辑控件中的值
SelectedIndex:获取或设置当前选择内容的索引
SelectedItems:获取包含与选定行对应的数据项的列表
SelectionMode:获取或设置数据网格的选择行为
Methods:
BeginEdit:设置当前单元格和当前行进入编辑模式
CancelEdit:取消当前编辑、恢复原始值并退出编辑模式。
OnAutoGeneratingColumn:引发AutoGeneratingColumn事件
OnBeginningEdit:引发BeginningEdit事件
OnCellEditEnded:引发CellEditEnded事件
OnCellEditEnding:引发CellEditEnding事件
OnColumnDisplayIndexChanged:引发ColumnDisplayIndexChanged事件
OnColumnReordered:引发ColumnReordered事件
OnColumnReordering:引发ColumnReordering事件
OnCurrentCellChanged:引发CurrentCellChanged事件
OnLoadingRow:引发LoadingRow事件
OnLoadingRowDetails:引发LoadingRowDetails事件
OnLoadingRowGroup:引发LoadingRowGroup事件
OnProperingCellForEdit:引发PreparingCellForEdit事件
OnRowDetailsVisibilityChanged:引发RowDetailsVisibilityChanged事件
OnRowEditEnded:引发RowEditEnded事件
OnRowEditEnding:引发RowEditEnding事件
OnSelectionChanged:引发SelectionChanged事件
SetBinding:设置提供的绑定对象
Events:
BeginningEdit:单元格或行进入编辑模式之前发生
CellEditEnded:提交或取消单元格编辑时发生
CellEditEnding:单元格编辑结束时发生
ColumnDisplayIndexChanged:在列的DisplayIndex属性更改时发生
ColumnHeaderDragCompleted:拖动列标题时发生
ColumnHeaderDragDelta:用户拖动列标题时发生一次或多次
ColumnHeaderDragStarted:开始拖动列标题时发生
ColumnReordered:列移至显示顺序中的新位置时发生
ColumnReordering:列移至显示顺序中的新位置之前发生
CurrentCellChanged:其他单元格成为单元格时发生
PreparingCellForEdit:当DataGridTemplateColumn中的单元格进入编辑模式时发生
RowDetailsVisibilityChanged:在RowDetailsVisibilityMode属性值更改时发生
RowEditEnded:提交或取消行编辑时发生
RowEditEnding:行编辑结束时发生
SelectionChanged:当SelectedItem或SelectedItems属性值更改时发生
-->
</Grid>

DataGrid.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DataGrid
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
List
<Employees> employee = new List<Employees>();
employee.Add(
new Employees("keysky", 24, "安徽",
"Like Programming,Reading,Football", true));
employee.Add(
new Employees("cat", 26, "北京",
"Like Testing,Dancing,Sports", true));
employee.Add(
new Employees("wj", 32, "湖南",
"Like Smoking,Managing,Sports", false));
employee.Add(
new Employees("ds", 35, "湖南",
"Like Reading,Managing,Sports", true));
myGrid.ItemsSource
= employee;
}

private void cbx1_Checked(object sender, RoutedEventArgs e)
{
if ((bool)cbx1.IsChecked)
{
cbx1.Content
= "取消编辑DataGrid";
myGrid.IsReadOnly
= false;
}
else
{
cbx1.Content
= "编辑DataGrid";
myGrid.IsReadOnly
= true;
}
}

private void myGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Employees employee
= myGrid.SelectedItem as Employees;
tbinfo.Text
= "名字:" + employee.Name + " 在职:" +
employee.Check
+ " 年龄:" + employee.Old + " 出生地:" +
employee.BirthPlace
+ " 爱好:" + employee.Selfinfo;
}
}
}

Employees.cs:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DataGrid
{
public class Employees
{
public string Name { get; set; }
public int Old { get; set; }
public string BirthPlace { get; set; }
public string Selfinfo { get; set; }
public bool Check { get; set; }
public Employees(string name, int old, string birthplace, string selfinfo, bool check)
{
this.BirthPlace = birthplace;
this.Name = name;
this.Old = old;
this.Selfinfo = selfinfo;
this.Check = check;
}
}

}

运行效果: