gpt4 book ai didi

c# - 在 XAML 中指定自定义转换器

转载 作者:太空狗 更新时间:2023-10-29 21:39:22 25 4
gpt4 key购买 nike

我在 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 中工作的所有数据绑定(bind)。这大概解释了我的部分问题。但我仍然不确定在 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]

关于c# - 在 XAML 中指定自定义转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23038086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com