以编程方式更改 DataGridRow 中的控件
我有一个 WPF DataGrid 包含一个产品列表,最后一列中有一个图像按钮,用于将产品项添加到 Orders_Products 集合中。那行得通。
现在,如果产品项已在 Orders_Products 集合中,我想将“添加”图像按钮更改为“删除”图像按钮。
我尝试使用 LoadingRow 事件,但似乎无法访问 Image 对象,因为在 LoadingRow 事件中尚未准备好...
我尝试了 Image 对象的 Load 事件,但如果行不可见,则不会触发它在表单中(当我必须滚动数据网格才能看到该行时)。当我对列进行排序并且该行在表单中直接可见时,它会触发。我快要疯了...:(
我想我没有做任何不寻常的事情,但我是 WPF 的新手,可能我错过了一些东西。
有人能给我一个提示吗? 提前致谢, Joe
P.S.:我正在使用实体框架。
I have a WPF DataGrid contains a list of Products with an image button in the last column to add the Product item into the Orders_Products collection. That works.
Now I'd like to change the "add" image button with a "delete" image button if the Product item is already in the Orders_Products collection.
I tried to use the LoadingRow event but it seems there's no way to access the Image object because is not ready yet in the LoadingRow event...
I tried the Load event of the Image object, but it's not fired if the row is not visible in the form (when I must scroll the datagrid to see that row). It fires when I sort a column and the row is directly visible in the form. I'm going crazy... :(
I think I'm not doing something unusual but I'm new to WPF and probably I miss something.
Can someone give me an hint?
Thanks in advance,
Joe
P.S.: I'm using Entity Framework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
执行此操作的正确方法是将 DataGrid 绑定到要显示的对象集合(您可能已经这样做了)。
然后,手动定义
DataGridTemplateColumn
并将其CellTemplate
设置为适当的DataTemplate
(这通常被定义为DataGrid 中的资源)
或元素逻辑树中更高的位置)。您可以查看如何完成上述操作的示例 此处。
在
DataTemplate
内,使用我对这个问题的回答中描述的技术来改变显示的内容通过匹配数据绑定Product
中适当属性的值来在模板中实现。所有这些都可以完全在 XAML 中完成,这是在 WPF 中执行操作的首选方式。
更新(工作示例)
Product
:MainWindow.xaml.cs
:MainWindow.xaml
:The proper way of doing this is by binding the
DataGrid
to the collection of objects you want to display (you are probably doing this already).Then, manually define a
DataGridTemplateColumn
and set itsCellTemplate
to an appropriateDataTemplate
(this would usually be defined as a resource in yourDataGrid
or somewhere higher in the logical tree of elements).You can see an example of how the above is done here.
Inside the
DataTemplate
, use the technique described in my answer to this question to vary what is displayed in the template by matching the value of an appropriate property in the databoundProduct
.All of this can be done entirely in XAML, as is the preferred way of doing things in WPF.
Update (working example)
The
Product
:MainWindow.xaml.cs
:MainWindow.xaml
: