Hun*_*unt 1 c# xamarin xamarin.forms
我试图改变Image源动态基于使用数据下载上Converters的Xamarin.Forms
从服务器获取数据的共有三种状态
1)成功下载数据时成功2)未下载数据且出现错误时错误3)进程空闲时
对于上述所有情况,我都使用不同的图标。
这是我的XAMLcode
<Image Source="{Binding CustomerState, Converter={StaticResource SyncConverter}}" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Grid.Column="0" HeightRequest="20" Margin="8,12,8,12" />
Run Code Online (Sandbox Code Playgroud)
这是我的转换器代码
public class SyncConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool? syncState = value as bool?;
if (syncState != null) {
if (syncState.Value) return "ic_success";
else return "ic_error";
}
return "ic_idle";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,如果CustomeState为null,则显示ic_idle图标;如果CuswtomerStat为true,则显示成功,否则显示错误。
我的视图模型代码
private bool? isCustomerState;
public bool? CustomerState
{
get { return isCustomerState; }
set
{
isCustomerState = value;
OnPropertyChanged("CustomerState");
}
}
Run Code Online (Sandbox Code Playgroud)
但是不知何故,xamarin将错误抛出get { return isCustomerState; },错误是
System.NullReferenceException:对象引用未设置为对象的实例。
您可以在使用前尝试验证“值”。就像是
public class SyncConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value != null){
bool? syncState = value as bool?;
if (syncState != null) {
if (syncState.Value) return "ic_success";
else return "ic_error";
}
}
return "ic_idle";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2122 次 |
| 最近记录: |