[英]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.