[英]image source in xaml depends on code behind variable
I have Image 我有图片
<Image HorizontalAlignment="Left" VerticalAlignment="Top" Source="" Width="20" Height="20" />
and I have variable bool IsOk in codebehind. 我在代码隐藏中有变量bool IsOk。 How can I bind it to source property and have condition that when it is true source will be "../Shared/Images/ok.png" and when false "../Shared/Images/cancel.png"?
我如何将其绑定到源属性,并具有以下条件:当源属性为true时,源将为“ ../Shared/Images/ok.png”,而为false“ ../Shared/Images/cancel.png”? Can I use to it triggers?
我可以使用它触发吗?
No need for a trigger. 无需触发。
Just bind the Image's Source property to a property on your ViewModel that returns either the ok image or the cancel image. 只需将Image的Source属性绑定到ViewModel上的属性即可,该属性返回确定的图像或取消的图像。
Modify your code so that whenever IsOk changes, a PropertyChanged event for your button image property is fired. 修改您的代码,以便每当IsOk更改时,都会触发按钮图像属性的PropertyChanged事件。 This way, the image will be updated automatically whenever you change the IsOk property.
这样,只要您更改IsOk属性,图像就会自动更新。 Something like this:
像这样:
public bool IsOk
{
get
{
return _isOk;
}
set
{
if (_isOk != value)
{
_isOk = value;
RaisePropertyChanged("IsOk");
RaisePropertyChanged("ButtonImage");
}
}
}
public Image ButtonImage
{
get
{
if (_isOk)
return _okImage;
else
return _cancelImage;
}
}
.. and then in your XAML: ..然后在您的XAML中:
<Image Source="{Binding ButtonImage}" ... />
Marty's answer is clean, but if you really just feel like using a trigger...something like this might work also, but like I said, Marty's is cleaner. 马蒂的答案很干净,但是如果您真的只是想使用扳机...类似的事情也可能起作用,但是就像我说的那样,马蒂的答案更干净。 :)
:)
<Image HorizontalAlignment="Left" VerticalAlignment="Top" Source="" Width="20" Height="20">
<i:Interaction.Triggers>
<ei:DataTrigger Value="False"
Binding="{Binding BooleanValueBinding}">
<ei:ChangePropertyAction PropertyName="Source"
Value="../Shared/Images/cancel.png" />
</ei:DataTrigger>
<ei:DataTrigger Value="True"
Binding="{Binding BooleanValueBinding}">
<ei:ChangePropertyAction PropertyName="Source"
Value="../Shared/Images/ok.png" />
</ei:DataTrigger>
</i:Interaction.Triggers>
</Image>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.