[英]WPF: Using binding in C#
我正在使用两列(ID,NAME)DataGrid,并希望用新值更新行。
我不确定如何在C#代码中使用绑定部分。
<DataGrid Name="dataGridUser" ItemsSource="{Binding}" VerticalAlignment="Top" Width="auto" Grid.RowSpan="2"/>
如何使用净值更新datagrid:
ID,名称123,Peter 345,Simon ....
所以给你一个例子,首先创建一个模型
public class User
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
然后在您的代码隐藏文件中创建该模型的ObservableCollection
private ObservableCollection<User> _myUsers;
public ObservableCollection<User> MyUsers
{
get
{
if (_myUsers == null)
{
_myUsers = new ObservableCollection<User>();
}
return _myUsers;
}
}
现在您可以将DataGrid绑定到此属性
<DataGrid Grid.Row="1" Name="dataGridUser" ItemsSource="{Binding MyUsers}" AutoGenerateColumns="True"/>
并且不要忘记设置DataContext
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"></Window>
如果将新用户添加到ObservableCollection MyUsers,它将立即显示在DataGrid中,但是如果更改现有用户的名字,则不会显示更改。 为此,您必须在模型中实现INotityPropertyChanged 。
但是,如果您打算开发一个更复杂的应用程序,我建议您看一下MVVM模式。
我个人很喜欢MVVM Light Toolkit,该视频应该可以使您很好地了解MVVM的全部含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.