gpt4 book ai didi

c# - 设计时的 MarkupExtension.ProvideValue(IServiceProvider serviceProvider)

转载 作者:行者123 更新时间:2023-11-30 22:14:37 25 4
gpt4 key购买 nike

如果您编写自己的 MarkupExtension,您可能会偶然发现 IServiceProvider serviceProvider 参数在设计时与运行时不同。例如,您无法获取 IRootObjectProvider。那么是否有关于参数对象实现哪些接口(interface)的文档,是否有任何解决方法来获取根对象?

最佳答案

写了一个小 helper 来查看有哪些服务可用:

public class ServiceExtension : MarkupExtension
{
public ServiceExtension()
{
}

public ServiceExtension(Type serviceType)
{
ServiceType = serviceType;
}

[ConstructorArgument("serviceType")]
public Type ServiceType { get; set; }

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public object Service { get; set; }

public override object ProvideValue(IServiceProvider serviceProvider)
{
if (ServiceType == null)
{
Service= "ServiceType == null";
return this;
}
var service = serviceProvider.GetService(ServiceType);
Service= service ?? "null";
return this;
}
}

<Style TargetType="{x:Type HeaderedContentControl}">
<Setter Property="Header" Value="{Binding ServiceType}" />
<Setter Property="Content" Value="{Binding Service}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type HeaderedContentControl}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Col1" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ContentPresenter Grid.Column="0"
Margin="0,0,5,0"
ContentSource="Header" />
<ContentPresenter Grid.Column="1" ContentSource="Content" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<ItemsControl Grid.IsSharedSizeScope="True">
<HeaderedContentControl DataContext="{local:Service {x:Type xaml:IXamlNameProvider}}" />
<HeaderedContentControl DataContext="{local:Service {x:Type xaml:IXamlNameResolver}}" />

<HeaderedContentControl DataContext="{local:Service {x:Type x:IProvideValueTarget}}" />
<HeaderedContentControl DataContext="{local:Service {x:Type x:IXamlTypeResolver}}" />
<HeaderedContentControl DataContext="{local:Service {x:Type x:IValueSerializerContext}}" />
<HeaderedContentControl DataContext="{local:Service {x:Type componentModel:ITypeDescriptorContext}}" />
<HeaderedContentControl DataContext="{local:Service {x:Type xaml:IDestinationTypeProvider}}" />

<HeaderedContentControl DataContext="{local:Service {x:Type xaml:IXamlNamespaceResolver}}" />
<HeaderedContentControl DataContext="{local:Service {x:Type xaml:IXamlSchemaContextProvider}}" />

<HeaderedContentControl DataContext="{local:Service {x:Type xaml:IRootObjectProvider}}" />
<HeaderedContentControl DataContext="{local:Service {x:Type x:IUriContext}}" />
<HeaderedContentControl DataContext="{local:Service {x:Type xaml:IAmbientProvider}}" />
</ItemsControl>

关于c# - 设计时的 MarkupExtension.ProvideValue(IServiceProvider serviceProvider),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18428384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com