![](/img/trans.png)
[英]call converter in XAML if property of a object in the observable collection changes
[英]Where to set the Converter for items of a collection in XAML
我剛剛將第一個轉換器從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)
{
}
}
在XAML中,我應該在哪里設置轉換器? 我在組合框的ItemsSource中嘗試過:
ItemsSource="{Binding YearsCollection, Converter={StaticResource intToStringYearConverter}}"
但是我總是在這一行得到InvalidcastException
:
int intY = (int)value;
問題是你試圖轉換整個集合而不是集合中的一個項目。
你會想做這樣的事情:
<ListBox ItemsSource="{Binding YearsCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border DataContext="{Binding Converter={StaticResource intToStringYearConverter}">
...
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
你不能像這樣使用轉換器,ItemsSource中的轉換器應該轉換整個集合,而不是單個項目。 集合對象不能轉換為整數,因此您將獲得異常。
您必須使用DataTemplate並將轉換器應用於單個項目。
或者 - 如果您需要將所有內容轉換為int - 您可以使用ItemStringFormat 。
此外,要在源為null時設置默認消息,可以使用Binding的TargetNullValue屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.