问题描述
我想合并来自两个不同ViewModel的DisplayName,但是只有在第一个不等于NullObject的情况下才可以.
I would like to combine the DisplayNames from two different ViewModels, but only IF the first is not equal to a NullObject.
我可以在转换器或父视图模型中轻松完成此操作,但希望我使用DataTrigger的尝试可以轻松解决.
I could easily do this in either a converter or a parent view model, but am hoping my attempt at using DataTrigger has an easy fix.
干杯,贝里
这什么也不显示:
<TextBlock Grid.Column="2" Grid.Row="0" >
<TextBlock.Inlines>
<Run Text="{Binding HonorificVm.DisplayName}"/>
<Run Text="{Binding PersonNameVm.DisplayName}"/>
</TextBlock.Inlines>
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding HonorificVm.Honorific}" Value="{x:Static model:Honorific.NullHonorific}">
<Setter Property="Text" Value="PersonNameVm.DisplayName"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
推荐答案
我将其分为两个TextBlocks
,仅使用触发器更改可见性.通过使用Inlines
并尝试在触发器中更改Text
,您可能会遇到优先级问题,并且Inlines
无法提取到Setter
.
I would split it into two TextBlocks
and only change the visibility using a trigger. By using the Inlines
and trying to change the Text
in the triggers you probably run into precedence problems and the Inlines
cannot be extracted to a Setter
.
例如
<StackPanel Grid.Column="2" Grid.Row="0" Orientation="Horizontal">
<TextBlock Text="{Binding HonorificVm.DisplayName}" Margin="0,0,5,0">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding HonorificVm.Honorific}"
Value="{x:Static model:Honorific.NullHonorific}">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<TextBlock Text="{Binding PersonNameVm.DisplayName}" />
</StackPanel>
另一个选择是MultiBinding
而不是Inlines
:
An alternative would be a MultiBinding
instead of Inlines
:
<TextBlock Grid.Column="2" Grid.Row="0">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Text">
<Setter.Value>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="HonorificVm.DisplayName" />
<Binding Path="PersonNameVm.DisplayName" />
</MultiBinding>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding HonorificVm.Honorific}"
Value="{x:Static model:Honorific.NullHonorific}">
<Setter Property="Text" Value="{Binding PersonNameVm.DisplayName}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
这篇关于TextBlock样式触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!