Adr*_*ian 3 c# wpf xaml converter
我刚刚将第一个转换器从int转换为string.我有一个带有整数的组合框填充(年),但如果值为0,我希望组合框显示"全部".
这是我的转换器:
public class IntToString : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
int intY = (int)value;
if (intY == 0)
{
String strY = "All";
return strY;
}
else
{
return intY.ToString();
}
}
return String.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
}
}
Run Code Online (Sandbox Code Playgroud)
在XAML中,我应该在哪里设置转换器?我在组合框的ItemsSource中尝试过:
ItemsSource="{Binding YearsCollection, Converter={StaticResource intToStringYearConverter}}"
Run Code Online (Sandbox Code Playgroud)
但我总是InvalidcastException这样做:
int intY = (int)value;
Run Code Online (Sandbox Code Playgroud)
问题是你试图转换整个集合而不是集合中的一个项目.
你会想做这样的事情:
<ListBox ItemsSource="{Binding YearsCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border DataContext="{Binding Converter={StaticResource intToStringYearConverter}">
...
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3726 次 |
| 最近记录: |