您的位置:首页 > 其它

DataGrid 数据绑定使用小结三(数据绑定)

2012-01-11 09:54 288 查看
上一节记录了数据绑定的自定义模板,可以在显示和编辑模板中添加任意控件实现业务需求,但出现一个问题

在编辑模板中进行编辑后却没有影响数据对象.这里要讲的是绑定的三种模式OneTime,OneWay,TwoWay

OneTime模式是在数据加载的时候显示数据,不影响数据对象也不被数据对象影响

OneWay模式受数据对象的变化而变化

TwoWay模式可以影响数据对象,也可以被数据对象影响

在上一节的代码中没有指定绑定的Mode(绑定模式),即系统默认为OneWay

但这里的绑定模式对数据对象有个要求,就是它要实现INotifyPropertyChange接口,(通知属性修发)

如果数据对象没有继承该接口,则数据对象改变后不会通知数据绑定控件属性修改事件

在继承了该接口后,上述三种模式才会显示其作用

数据对象类

View Code

public partial class DataGridBook2 : UserControl
{
List<BookClass2> list = new List<BookClass2>()
{
new BookClass2(true, "坏蛋是怎样炼成的", "tnspop","这本书讲了谢文东是如何从一个弱者变成一个强者的",12),
new BookClass2(false, "咸郎平说", "tnsstar","这本书讲了一些常见的经济问题,分析的很透彻",43),
new BookClass2(true, "帝国主义在中国", "tnssun","这本书讲了那些资本投资的金融学家在中国的一些见不得光的事情",26)
};
BookClass2 bc;
public DataGridBook2()
{
InitializeComponent();
Databinding();
}

private void Databinding()
{

gridSetColumns.ItemsSource = list;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
if (gridSetColumns.SelectedIndex == -1)
{
MessageBox.Show("请选择一行");
return;
}
bc = list[gridSetColumns.SelectedIndex];
stackJC.DataContext = bc;
}

/// <summary>
/// 修改数据对象
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnUpdate_Click(object sender, RoutedEventArgs e)
{
if (bc == null)
return;
bc.IsSelect = chkisselct.IsChecked.Value;
bc.Author = txtauthor.Text;
bc.Entity = txtentity.Text;
bc.Price = double.Parse(txtprice.Text);
bc.SendMessage = txtsendmessage.Text;
bc.Time = DateTime.Parse(txttime.Text);
bc.Title = txttitle.Text;
}

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
(gridSetColumns.SelectedItem as BookClass2).Author = ((sender as ComboBox).SelectedItem as Auth).AuthName;
}
}


通过这个案例,我们可以看到

Mode=OneWay,则数据对象改变则可以影响DataGrid行,DataGrid行中修改数据不会影响数据对象

Mode=OneTime,则数据对象改变不会影响DataGrid行,DataGrid行中修改数据不会影响数据对象

Mode=TwoWay,则数据对象改变可以影响DataGrid行,DataGrid行中修改数据可以影响数据对象

在你双击行的时候如果有编辑模板的话,会从数据对象中重新获取数据.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: