简体   繁体   中英

How to access converter from code in XAML?

I have a converter in the code behind called StringToIntConverter I try using it in xaml binding like this where s is the project namespace:

Converter={s:StringToIntConverter}

But it says that it is missing an assembly reference. What am I doing wrong?

I know there is some way to put it as a resource and then reference the resource but I am not sure how to do it.

<Some.Resources>
    <s:StringToIntConverter x:Key="StringToIntConverter"/>
</Some.Resources>
<!-- ... -->
Converter={StaticResource StringToIntConverter}

Curly braces indicate a markup extension , they cannot just be used arbitrarily to instantiate objects, but for convenience you could turn your converter into a markup extension.

Something like:

public class StringToIntConverter : MarkupExtension, IValueConverter
{
    //...

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

Then the code you used would work just fine!


Also note that you could use the binding in XML-element syntax to instantiate converters in place as well, eg

<TextBox>
    <TextBox.Text>
        <Binding Path="String">
            <Binding.Converter>
                <s:StringToIntConverter />
            </Binding.Converter>
        </Binding>
    </TextBox.Text>
</TextBox>

Uhm - normally it goes something like this if I understand your question. You have created a converter right? In you XAML you need to add a reference to the assembly like this.

xmlns:converters="clr-namespace:Shared.Converters;assembly=Shared"

even if it is in the same assembly - something like...

xmlns:local="clr-namespace:ItemMaster"

Now you need to create a staticResource for whatever converter you want to use.

<converters:CostMethodToBooleanConverter x:Key="CostMethodToBooleanConverter"/>

Then you can use it.

IsEnabled="{Binding SelectedItem, Converter={StaticResource ReverseCostMethodToBooleanConverter}, ElementName=OemOriginalCostMethod}"/>

Does that help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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