当ListView为空时如何通过触发器更改按钮图像
我想将 ListView
上的 WPF Button
图像更改为空,但现在不知道我必须从触发器中设置哪个属性。
<Style x:Key="DisableOnEmptyLvStyle" TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=myListView, Path=Items.Count}" Value="0">
<Setter Property="IsEnabled" Value="False"/>
<!-- which button property I must set here? -->
</DataTrigger>
</Style.Triggers>
</Style>
<Button Style="{StaticResource DisableOnEmptyLvStyle}">
<Image Source="{StaticResource myImage}"/>
</Button>
一旦 ListView
有项目,则图像必须更改为正常图像。
有什么想法如何做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您永远不应该使用
Style
直接设置Content
,因为Style
实例化一次并可能在多个控件中重复使用。问题在于,您在Setter
中为Content
分配的值也会实例化一次并共享,但一个控件只能有一个WPF 中的父级。会出现什么问题?如果您设置或更改样式中的
Content
并为多个Button
等引用它,您将看到只有最后一个按钮显示图像。第一个按钮将其图像设置为Content
,然后下一个按钮将图像设置为Content
并有效删除第一个按钮的内容。您可以考虑两种选择。
将图像创建为资源,并通过设置
x:Shared
属性设置为False
。<块引用>
当设置为
false
时,会修改 WPF 资源检索行为,以便对属性资源的请求为每个请求创建一个新实例,而不是为所有请求共享同一实例。创建数据模板并交换它们。这是有效的,因为 - 顾名思义 - 它们是模板,并且其控件将为它们应用到的每个控件进行实例化。
You should never set the
Content
directly using aStyle
, simply because theStyle
is instantiated once and potentially reused across multiple controls. The issue is that the value that you assign in theSetter
forContent
is also instantiated once and shared, but a control can only have a single parent in WPF.What can go wrong? If you set or change the
Content
in a style and reference it for e.g. multipleButton
s you will see that only the last button shows the image. The first button gets its image set asContent
, then the next button sets the image asContent
and effectively removes the content of the first button.There are two options that you can consider.
Create the images as resources and force each reference in XAML to get a new instance of the image by setting the
x:Shared
attribute toFalse
.Create data templates and swap them out. This works because - as the name says - they are templates and its controls will be instantiated for each control they are applied to.
请尝试以下操作:
Please try the following: