在XAML中指定自定义转换器

7

我有一个转换器类在Windows Store应用程序中:

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();
    }
  }
}

我现在正尝试在xaml中使用它。我无法想出正确的语法来告诉xaml使用我的转换器。

  <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem" >
      <Setter Property="Background" Value="{Binding Source=BackgroundColor, UpdateSourceTrigger=PropertyChanged, Converter=????????????????}"/>
    </Style>
  </ListView.ItemContainerStyle>
编辑:显然,Windows Store应用程序不允许开发人员使用在WPF中工作的所有数据绑定。这可能部分解释了我的问题。但我仍然不确定在Windows 8.1更新后是否会继续保持这种情况。
1个回答

9

通常的做法是在控件资源中声明您的转换器实例,然后将其作为静态资源引用。作为其中的一部分,如果您还没有定义XML命名空间别名,则必须定义它(请注意,如果命名空间不在当前程序集中,则只需指定程序集)。以下是一个部分示例:

<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]

这让我接近了——转换器现在尝试执行,谢谢。但它的输入值是字符串“BackgroundColor”,因此自然会抱怨它的输入不是Windows.UI.Color类型的对象。可能相关的事实是:这是一个Windows Store应用程序。我将编辑我的问题和您的回答以考虑到这一点。 - William Jockusch
@WilliamJockusch 将 Source=BackgroundColor 更改为 Path=BackGroundColor,并确保您的视图模型中有一个名为 BackgroundColor 的属性。当我复制/粘贴您的代码时,我错过了这一点。Source 暗示要绑定到现有源对象,而 Path 指定当前绑定对象上的路径(默认情况下是 DataContext)。也就是说,只有在您打算更改项目绑定的对象时才使用 Source - slugster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接