我在WPF应用程序中有一个Datagrid控件,我正尝试将该控件绑定到主窗口类中的ObservableCollection属性。我尝试绑定的属性定义为:
private ObservableCollection<RequestResult> m_SentRequests = new ObservableCollection<RequestResult>();
public ObservableCollection<RequestResult> SentRequests { get { return m_SentRequests; } }我的datagrid在一个组中,其中的datacontext设置为MainWindow:
<GroupBox Header="Results" Height="275" HorizontalAlignment="Stretch" Margin="0,305,0,0" Name="grpResults" VerticalAlignment="Top" Width="712" DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:MainWindow, AncestorLevel=1}}">
<Grid>
<DataGrid AutoGenerateColumns="False" Height="246" HorizontalAlignment="Stretch" Margin="6,6,6,0" Name="dgResults" VerticalAlignment="Top" ItemsSource="{Binding Path=SentRequests}" DataContext="{Binding}" IsSynchronizedWithCurrentItem="True" />
</Grid>
</GroupBox>我遇到的问题是,在属性窗口中,在我选择SentRequests作为我的ItemsSource之后,我仍然不能选择“编辑属性绑定列”选项。我收到一个“您必须先设置ItemsSource才能执行此操作”对话框。当选择"Generate Columns“和"Remove Columns”时,我得到相同的错误。就好像我没有在我的对话框的ItemsSource属性中设置任何东西。
但是,我可以将AutoGenerateColumns设置为true,并且我看到我的数据被绑定了(但是,并没有绑定我想要显示的列)。
我是WPF的新手,我只是写这篇文章作为测试windows服务的快速测试应用。
有人知道我做错了什么吗?
发布于 2011-05-11 00:55:21
我认为您的itemSource中不需要Path参数。您应该能够仅将绑定设置为绑定{ItemsSource= SentRequests}
您还可以在代码中绑定到网格项源代码,例如,如果我创建了一个虚拟集合:
public class People
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Age { get; set; }
public string address { get; set; }
public string zip { get; set; }
}然后填充它
this.AllPeople = new ObservableCollection<People>();
private void FillData()
{
People p1 = new People();
p1.FirstName = "John";
p1.LastName = "Doe";
p1.Age = "24";
p1.address = "123 Main Street";
p1.zip = "11111";
People p2 = new People();
p2.FirstName = "Jane";
p2.LastName = "Smith";
p2.Age = "36";
p2.address = "456 Water Street";
p2.zip = "22222";
People p3 = new People();
p3.FirstName = "Larry";
p3.LastName = "Williams";
p3.Age = "24";
p3.address = "785 Water Street";
p3.zip = "33333";
this.AllPeople.Add(p1);
this.AllPeople.Add(p2);
this.AllPeople.Add(p3);
}然后,我可以将主页面构造器或方法中的项源设置为:
this.gridviewname.ItemsSource = "AllPeople";
发布于 2011-03-29 06:32:45
这可能是设计者在不不断编译的情况下渲染的一些技巧的结果(比如跳过代码隐藏构造函数)。尝试将您的集合移动到一个单独的类中,并使用该类的一个实例作为您的DataContext (类似于MVVM ViewModel)。另一个类应该能够正常初始化并向设计器提供绑定属性。
发布于 2011-03-29 03:31:59
你有没有尝试过不使用DataContext标签?在GroupBox和DataGrid中都有。
编辑
如下所示:
<GroupBox Header="Results" Height="275" HorizontalAlignment="Stretch" >
<Grid>
<DataGrid AutoGenerateColumns="False" Height="246" HorizontalAlignment="Stretch" Name="dgResults" VerticalAlignment="Top" ItemsSource="{Binding Path=SentRequests}" IsSynchronizedWithCurrentItem="True" />
</Grid>
</GroupBox>https://stackoverflow.com/questions/5463978
复制相似问题