wpf TextBlock 样式触发器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11197474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TextBlock style triggers
提问by Berryl
I would like to combine the DisplayNames from two different ViewModels, but only IF the first is not equal to a NullObject.
我想组合来自两个不同 ViewModel 的 DisplayNames,但仅当第一个不等于 NullObject 时。
I couldeasily do this in either a converter or a parent view model, but am hoping my attempt at using DataTrigger has an easy fix.
我可以在转换器或父视图模型中轻松完成此操作,但希望我尝试使用 DataTrigger 时可以轻松修复。
Cheers, Berryl
干杯,贝瑞尔
This displays nothing at all:
这根本不显示任何内容:
<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>
回答by H.B.
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 precedenceproblems and the Inlines
cannot be extracted to a Setter
.
我会将它分成两部分,TextBlocks
并且只使用触发器更改可见性。通过使用Inlines
和 尝试更改Text
触发器中的 ,您可能会遇到优先级问题并且Inlines
无法将 提取到Setter
.
e.g.
例如
<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>
An alternative would be a MultiBinding
instead of Inlines
:
另一种选择是MultiBinding
代替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>