我正在使用带有 TextBlock 元素的 UserControl 进行WPF应用程序。这些元素的内容取决于视图模型中的枚举(成功,待定,错误等)。
以下是TextBlock的不同状态的一些示例:
示例1 - 简单
<TextBlock>
Please wait
</TextBlock>
示例2 - 使用超链接
<TextBlock>
Searching for item. <Hyperlink Command="{Binding DetailsCommand}">Link to details</Hyperlink>
</TextBlock>
示例3 - 使用换行符
<TextBlock>
The content has been uploaded<LineBreak />
The item is not ready to use
</TextBlock>
根据视图模型中枚举的状态,动态更改此元素内容的最佳方法是什么?如果我将Text属性绑定到视图模型中的字符串,我认为我不能插入像 Hyperlink , LineBreak 等子元素。有哪些选项我有吗?
答案 0 :(得分:3)
我会用TemplateSelector实现它:
public class TemplSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var element = container as FrameworkElement;
if (element != null && item != null)
{
var vm = (ViewModel)item;
if (vm.YourEnum == 1)
return element.FindResource("templ1") as DataTemplate;
else if (vm.YourEnum == 0)
return element.FindResource("templ0") as DataTemplate;
}
return null;
}
}
<Window.Resources>
<local:TemplSelector x:Key="templSel"/>
</Window.Resources>
<ContentPresenter ContentTemplateSelector="{StaticResource templSel}" Content="{Binding ViewModel}">
<ContentPresenter.Resources>
<DataTemplate x:Key="templ0">
<TextBlock>
Please wait
</TextBlock>
</DataTemplate>
<DataTemplate x:Key="templ1">
<TextBlock>
Searching for item. <Hyperlink Command="{Binding DetailsCommand}">Link to details</Hyperlink>
</TextBlock>
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
答案 1 :(得分:2)
您可以使用Label作为主机,并根据触发器
设置模板 <Label>
<Label.Style>
<Style TargetType="Label">
<Style.Triggers>
<DataTrigger Binding="{Binding YourEnum}" Value="something">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<TextBlock>
Please wait
</TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding YourEnum}" Value="somethingElse">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<TextBlock>
Searching for item. <Hyperlink Command="{Binding DetailsCommand}">Link to details</Hyperlink>
</TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding YourEnum}" Value="else">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<TextBlock>
The content has been uploaded<LineBreak />
The item is not ready to use
</TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>