在按钮上显示图像或文本 [英] Show Image or Text on button
问题描述
我试图弄清楚这将如何实现;
我有一个按钮,如果viewmodel的ImageSource属性不为null,我想向该按钮添加图像.如果ImageSource等于null,则将按钮的内容绑定到同一viewmodel的"DisplayName"属性.
I''m trying to figure out how this would be possible to accomplish;
I have a button, if the ImageSource property of a viewmodel is not null I would like to add an image to this button. if ImageSource is equal to null I would bind the content of the button to "DisplayName" property of the same viewmodel.
Would this be possible ?
推荐答案
我认为可以通过设置触发器来完成.
在IsImageSourceNull上触发一个触发器,然后在ViewModel中创建该属性.如果为true,则将按钮内容设置为DisplayName;如果为false,则将其设置为图像.
I think it could be done with a setter trigger.
Make a trigger on IsImageSourceNull and create that property in the ViewModel. If true set button content to DisplayName if false set it to the image.
我不知道您的设计是否符合以下要求.请尝试以下方法.
创建数据模板,如下所示
Hi,
I dont know whether your design is suited the below impementation.Try the following.
create a data template as follows
<DataTemplate x:Key="MyButtonContentTemplate" DataType="{x:Type local:YourViewModelObject}">
<Grid>
<TextBlock x:Name="txt" Text="{Binding display_name}"/>
<Image x:Name="img" Source="{Binding image_source}"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding image_source}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed" TargetName="img"/>
</DataTrigger>
<DataTrigger Binding="{Binding display_name}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed" TargetName="txt"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
然后将内容设置为您的视图模型对象,并将内容模板应用为上述模板.
< Button ContentTemplate ="{StaticResource MyButtonContentTemplate}" x:Name ="btn" Width ="100" Height ="50"/>
then set the content as your view model object and apply the content template as the above template.
<Button ContentTemplate="{StaticResource MyButtonContentTemplate}" x:Name="btn" Width="100" Height="50"/>
btn.Content = YourViewModelObject;
这篇关于在按钮上显示图像或文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!