简体   繁体   English

以编程方式在Silverlight中使用C#中的值转换器

[英]programmatically using a value converter in C# in Silverlight

I have a C# Silverlight application. 我有一个C#Silverlight应用程序。 In this application I have defined a value converter that I am using in the XAML. 在这个应用程序中,我已经定义了一个我在XAML中使用的值转换器。 I have run into a situation where I need to programmatically use this value converter in my code behind. 我遇到了一种情况,我需要以编程方式在我的代码后面使用这个值转换器。 My question is, how do I do that? 我的问题是,我该怎么做? In XAML, I am using my value converter as follows: 在XAML中,我正在使用我的值转换器,如下所示:

<TextBlock x:Name="myTextBlock" Text="{Binding Mode=OneWay, Path=FirstName, Converter={StaticResource myConverter}, ConverterParameter=NotSet}" />

How do I use this converter in my code-behind? 如何在我的代码隐藏中使用此转换器?

Thanks! 谢谢!

If you just want to call the converter explicitly in the code behind, just use the converter class just like any other class and call its Convert() methos with appropriate parameters 如果您只想在后面的代码中显式调用转换器,只需像使用其他类一样使用转换器类,并使用适当的参数调用其Convert()方法

YourConverter conv = new YourConverter();
conv.Convert(...)

I personally add a static method to the converter like so: 我个人在转换器中添加一个静态方法,如下所示:

public static object Convert(object value)
{
    return new MyConverter().Convert(value, null, null, CultureInfo.CurrentCulture);
}

You can then use this in code like so: 然后,您可以在代码中使用它,如下所示:

MyConverter.Convert(valueToConvert);

You can even change the return type and cast the result before returning to make usage easier. 您甚至可以在返回之前更改返回类型并转换结果,以便更轻松地使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM