[英]Binding with ValueConverter not updating in UI after value change
我有这个XAML
<Label
x:Name="lblStatus"
FontSize="Small"
LineBreakMode="NoWrap"
Text="{Binding ., Mode=OneWay, StringFormat='Status: {0}', Converter={views:JobStatusConverter}}" />;
我有JobViewModel绑定到它。
我已经使用了通知属性更改OnPropertyChanged(new PropertyChangedEventArgs(String.Empty)); 在财产设定者中,但仍然没有成功。 这是我的转换器
public class JobStatusConverter : IMarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is JobModel model)
{
if (!model.IsActive)
{
return "Notactive";
}
if (model.IsDone)
{
return "Closed";
}
return "Open";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => null;
public object ProvideValue(IServiceProvider serviceProvider) => this;
public bool Invert { get; set; }
}
这是我的模型代码
public class JobViewModel : ObservableObject
{
private JobModel Model { get; set; }
public bool IsActive =>
Model?.IsActive ?? false;
public bool IsDone =>
Model?.IsDone ?? false;
public void ReceiveData()
{
try
{
Model = GetJobData("JB001");
}
catch (Exception ex)
{
}
finally
{
OnPropertyChanged(new PropertyChangedEventArgs(String.Empty));
}
}
}
从命令调用ReceiveData()后,所有其他UI值都会更新,但不会更新lblStatus值。为什么这不起作用?
propertyName参数的Empty值或null表示所有属性均已更改。
但是您不绑定任何属性,而是绑定到模型本身。 在您的特定情况下,您可以绑定到IsActive
,稍微更改一下转换器,它应该可以工作。
原因: Label的BindingContext
是JobViewModel
,而不是JobModel
。因此将永远不会调用转换中的逻辑。
由于使用了数据绑定,因此可以在JobViewModel
设置标签Text
。
Text={Binding Content}
public class JobViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string content;
public string Content
{
get
{
return content;
}
set
{
if (content != value)
{
content = value;
NotifyPropertyChanged();
}
}
}
private JobModel Model { get; set; }
public bool IsActive =>
Model?.IsActive ?? false;
public bool IsDone =>
Model?.IsDone ?? false;
public JobViewModel()
{
if (!Model.IsActive)
{
Content = "Status:Notactive";
}
if (Model.IsDone)
{
Content = "Status:Closed";
}
Content = "Status:Open";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.