【问题标题】:Specify a custom converter in XAML在 XAML 中指定自定义转换器
【发布时间】:2014-04-13 01:27:22
【问题描述】:

我在 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 更新后这种情况是否会继续存在。

【问题讨论】:

    标签: c# wpf xaml binding windows-store-apps


    【解决方案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]
    

    【讨论】:

    • 这让我很接近——转换器现在确实尝试执行,谢谢。但是它的输入值是字符串“BackgroundColor”,所以它自然会抱怨它的输入不是Windows.UI.Color类型的对象。可能相关的事实:这是一个 Windows 应用商店应用程序。我将编辑我的问题和您的回答以考虑到这一点。
    • @WilliamJockusch 将 Source=BackgroundColor 更改为 Path=BackGroundColor 并确保您的视图模型上有一个名为 BackgroundColor 的属性。当我复制/粘贴您的代码时,我错过了。 Source 推断要绑定到的现有源对象,而Path 指定当前绑定对象上的路径(默认情况下是 DataContext)。如果您打算更改项目绑定到的对象,IOW 仅使用Source
    猜你喜欢
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 2016-04-19
    • 2012-03-15
    • 2021-01-28
    相关资源
    最近更新 更多