How can I refer to a binding converter in a different namespace in Silverlight XAML?
Since you cannot apparently create a Silverlight DataTemplate in C #, I am trying to create it in XAML. I have a converter that I need to refer to, which I have defined in C # in a different namespace. I've tried doing this:
<UserControl.Resources>
<DataTemplate x:Key="PriceTemplate">
<TextBlock Text="{Binding Price, Converter={Converters:PriceConverter}}" />
</DataTemplate>
</UserControl.Resources>
Where converters are xmlns which points to the correct namespace. However, I am getting a compilation error that reads:
The Converters: PriceConverter type is used as a markup extension, but does not derive from the MarkupExtension.
I tried to add System.Windows.Markup.MarkupExtension as a parent for my converter, but apparently it doesn't exist in Silverlight.
How can I reference my converter in XAML without rewriting it in XAML?
a source to share
First you want to make a static resource and then bind to the converter, which is a static resource.
<UserControl.Resources>
<conv:IntConverter x:Key="IntConverter"></conv:IntConverter>
</UserControl.Resources>
<StackPanel>
<TextBlock x:Name="Result" Margin="15" FontSize="20"
HorizontalAlignment="Center" VerticalAlignment="Center"
Text="{Binding Converter={StaticResource IntConverter}}">
</TextBlock>
</StackPanel>
</Window>
So the "conv:" xml namespace was registered at the top of the document, just like with custom controls:
xmlns:conv="clr-namespace:MyFooCompany.Converters"
This example is adapted from the tutorial below on the same issue for WPF:
http://www.dev102.com/2008/07/17/wpf-binding-converter-best-practices/
a source to share
You seem to be confusing types with instances. In the envelope, the type will exist "in" the namespace, but we do not specify the type in the bindingas a converter. Instead, we are giving a binding for an actual instance of that type.
Instances IValueConverter
are usually stateless , so we can store a shared instance in whatever chain of available resource dictionaries where the DataTemplate instance is loaded.
In xaml, we can refer to another namespace by creating a new alias to cover it. With that in mind, your xaml might look something like this: -
<UserControl x:Class="SilverlightApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication1"
xmlns:localConverters="clr-namespace:SilverlightApplication1.Converters">
<UserControl.Resources>
<localConverters:PriceConverter x:Key="PriceConverter" />
<DataTemplate x:Key="Test">
<TextBlock Text="{Binding Price, Converter={StaticResource PriceConverter}}" />
</DataTemplate>
</UserControl.Resources>
a source to share