简体   繁体   中英

Using converter to a TextBlock in a DataTemplate

I'm binding a collection of strings using an ItemsControl :

<ItemsControl ItemsSource="{Binding MyCollection}">
     <ItemsControl.Template>
          <ControlTemplate>
                <ItemsPresenter/>
          </ControlTemplate>
     </ItemsControl.Template>
 <ItemsControl.ItemTemplate>
        <DataTemplate>
             <TextBlock Text="{Binding, Converter={local:MyTextConverter}}" />
        </DataTemplate>
 </ItemsControl.ItemTemplate>
 </ItemsControl>

The code above does not compile because of the syntax {Binding, Converter=...} , how can I use the converter in this case?

You would usually declare the converter as resource and do a StaticResource lookup:

<Window.Resources>
    <local:MyTextConverter x:Key="MyTextConverter"/>
</Window.Resources>
...
<TextBlock Text="{Binding, Converter={StaticResource MyTextConverter}}" />

You could make the other syntax work if your converter would derive from MarkupExtension and override the ProvideValue method. But this isn't common practice.

public class MyTextConverter: MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
    ...
}

尝试使用在资源中声明了YourConverterKey Converter="{StaticResource YourConverterKey}" ,如下所示:

<Local:MyTextConverter x:Key="YourConverterKey"></Local:MyTextConverter>

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