繁体   English   中英

在XAML中指定自定义转换器

[英]Specify a custom converter in XAML

我在Windows应用商店应用中有一个转换器类:

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应用商店应用程序不允许开发人员使用在WPF中工作的所有数据绑定。 这可能解释了我的部分问题。 但我仍然不确定在Windows 8.1更新之后是否会继续如此。

执行此操作的常规方法是在控制资源中声明转换器的实例,然后将其作为静态资源引用。 作为其中的一部分,如果您还没有定义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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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