本文介绍了从代码中设置自定义的MarkupExtension的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您设置代码的自定义的MarkupExtension 怎么办?

How do you set a custom MarkupExtension from code?

您可以轻松地设置如果XAML的。这同样适用于绑定 DynamicResource

You can easily set if from Xaml. The same goes for Binding and DynamicResource.

<TextBox FontSize="{Binding MyFontSize}"
         Style="{DynamicResource MyStyle}"
         Text="{markup:CustomMarkup}"/>



设置通过代码相同的价值观背后需要一点点不同的方法

Setting the same values through code behind requires a little different approach


  1. 绑定:使用textBox.SetBinding或BindingOperations.SetBinding

  1. Binding: Use textBox.SetBinding or BindingOperations.SetBinding

Binding binding = new Binding("MyFontSize");
BindingOperations.SetBinding(textBox, TextBox.FontSizeProperty, binding);


  • DynamicResource:使用SetResourceReference

  • DynamicResource: Use SetResourceReference

    textBox.SetResourceReference(TextBox.StyleProperty, "MyStyle");
    


  • CustomMarkup:如何设置自定义的的MarkupExtension ?我应该叫 ProvideValue ,它那种情况下,我怎么得到一个保持的的IServiceProvider *?

  • CustomMarkup: How do I set a custom MarkupExtension from code? Should I call ProvideValue and it that case, how do I get a hold of a IServiceProvider?*

    CustomMarkupExtension customExtension = new CustomMarkupExtension();
    textBox.Text = customExtension.ProvideValue(??);
    


  • 我发现令人惊讶的一点关于这个问题的话,能不能做到?

    I found surprisingly little on the subject so, can it be done?

    HB 已经回答了这个问题。只是增加了一些细节在这里我为什么要这么做。我试图创建下列问题的方法。

    H.B. has answered the question. Just adding some details here to why I wanted to do this. I tried to create a workaround for the following problem.

    的问题是,你不能从导出绑定并覆盖 ProvideValue ,因为它是密封的。你必须做这样的事情,而不是:


  • 的巨大的限制
  • (在评论)

    • WPF: Markup Extension in Data Trigger
    • Huge limitation of a MarkupExtension
    • A base class for custom WPF binding markup extensions (in the comments)

    不过,这只能当 TargetProperty 的类型为对象,否则异常又回来了。如果你看一下源代码 BindingBase 你可以看到,这不正是这一点,但它出现在框架有一些秘密的成分,使得它的工作。

    However, that only works when the TargetProperty is of type object, otherwise the exception is back. If you look at the source code for BindingBase you can see that it does exactly this but it appears the framework has some secret ingredient that makes it work.

    推荐答案

    我觉得没有代码相同,则该服务只能通过XAML。从:

    I think there is no code-equivalent, the services are only available via XAML. From MSDN:

    的MarkupExtension只有一个虚方法,ProvideValue。输入的ServiceProvider参数是怎样的服务传达给当标记扩展是通过XAML处理器称为实现。

    这篇关于从代码中设置自定义的MarkupExtension的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    10-29 13:51