WPF的datagrid如何手动绑定列?
datagrid自动生成的列都是可编辑的,我想让其中的某些列变成readonly,需要手动建立列并且设定属性。但是不知为何运行时会抛出“在使用 ItemsSource 之前,项集合必须为空。”的异常。如果去掉那句itemssource="{binding}"的话不会抛出异常,但是又显示不出自定义的列。请高手帮忙看看怎么解决,谢谢!
ps:我可以在自动生成列之后用c#代码设定每个列的只读属性,但是我想把界面的东西都放在xaml里面做,我想知道这个问题应该怎么在xaml里面写
这是xaml文件
<Window x:Class="StyleTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:StyleTest"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding}" AlternatingRowBackground="Silver" AlternationCount="2" AutoGenerateColumns="False" Height="164" HorizontalAlignment="Left" Margin="0,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="342" CanUserAddRows="False" CanUserDeleteRows="False">
<DataGridTextColumn Header="Name" Binding="{Binding Source=Persons2, Path=Name}"></DataGridTextColumn>
<DataGridTextColumn Header="Age" Binding="{Binding Source=Persons2, Path=Age}"></DataGridTextColumn>
</DataGrid>
</Grid>
</Window>
这是c#代码
namespace StyleTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
ObservableCollection<Person2> mPersons2=new ObservableCollection<Person2>();
ObservableCollection<Person2> Persons2
{
get
{
return this.mPersons2;
}
}
public MainWindow()
{
InitializeComponent();
this.Persons2.Add( new Person2( "tianfang", 25, 1.73 ) );
this.Persons2.Add( new Person2( "liubo", 28, 1.82 ) );
this.dataGrid1.DataContext = Persons2;
}
}
public class Person2:INotifyPropertyChanged
{
pub