问题描述
我试图弄清楚这将如何实现;
我有一个按钮,如果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 ?
推荐答案
<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;
这篇关于在按钮上显示图像或文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!