Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify a custom converter in XAML

I have a converter class in a Windows Store App:

namespace MyNamespace {
  public class ColorToBrushConverter : IValueConverter {

    public object Convert(object value, Type targetType, object parameter, string language) {
      if (value is Windows.UI.Color) {
        Windows.UI.Color color = (Windows.UI.Color) value;
        SolidColorBrush r = new SolidColorBrush(color);
        return r;
      }
      CommonDebug.BreakPoint("Invalid input to ColorToBrushConverter");
      throw new InvalidOperationException();
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language) {
      throw new NotImplementedException();
    }
  }
}

I am now trying to use it in xaml. I cannot figure out the right syntax for the xaml to tell it to use my converter.

  <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem" >
      <Setter Property="Background" Value="{Binding Source=BackgroundColor, UpdateSourceTrigger=PropertyChanged, Converter=????????????????}"/>
    </Style>
  </ListView.ItemContainerStyle>

EDIT: Apparently, Windows Store Apps do not allow the developer to use all Data Bindings that work in WPF. That presumably explains part of my problem. But I am still unsure whether or not this will continue to be the case after the Windows 8.1 Update.

like image 610
William Jockusch Avatar asked Apr 13 '14 01:04

William Jockusch


1 Answers

The normal way to do this is to declare an instance of your converter in the control resources, then reference it as a static resource. As part of this you will have to define an XML namespace alias if you haven't already (note that the assembly only has to be specified if the namespace isn't in the current assembly). Here's a partial example:

<Window x:Class="....etc..."

        xmlns:Converters="clr-namespace:MyNamespace;[assembly=the assembly the namespace is in]"
        />

<Window.Resources>
    <Converters:ColorToBrushConverter x:Key="MyColorToBrushConverter" />
</Window.Resources>

<Grid>
    <ListView>
        [snip]
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem" >
                <Setter Property="Background" 
                        Value="{Binding Path=BackgroundColor, 
                                        UpdateSourceTrigger=PropertyChanged, 
                                        Converter={StaticResource MyColorToBrushConverter}
                               }"
                        />
            </Style>
        </ListView.ItemContainerStyle>
        [snip]
like image 52
slugster Avatar answered Oct 20 '22 14:10

slugster