【发布时间】:2019-06-13 08:46:58
【问题描述】:
Binding works without INotifyPropertyChanged, why?
直接将我的 UI 绑定到 HTTP API 模型而不创建单独的视图模型是一种不好的做法吗?
唯一的缺点是它不会实现 INotifyPropertyChanged,因此当您从代码更改属性时 UI 不会更新 - 但是如果您不需要从代码更新属性怎么办?
这是我的 API 响应模型:
public class EventResponseModel
{
public int Id { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string ArgbColor { get; set; } // should bind to Brush
public Location Location { get; set; }
public IEnumerable<Person> Attendees { get; set; }
}
在上面的模型中,我有 ArgbColor 需要在 XAML 中绑定到 Brush。我可能可以创建 StringToBrushConverter : IValueConverter 来使其工作,而不是创建单独的视图模型。
这总是首选创建一个单独的视图模型,映射到它然后绑定到它吗?
对于编辑,我仍然有一个单独的虚拟机并使用如下组合:
public class EventVM
{
public EventResponseModel EditedEvent { get; set; }
// available locations etc., commands for saving
}
【问题讨论】:
-
“这是一种不好的做法吗?” - 不,在我看来不是。不过,我会推荐
public Color ArgbColor { get; set; }并绑定 SolidColorBrush 的 Color 属性。 -
Color需要引用System.Media或PresentationCore。这个模型是用在服务器上的,所以string是最好的类型。 -
ArgbColor值是否包含 html clr 代码?像这样(#1A85CD)? -
@AvinashReddy 是的,#AARRGGBB。使用
BrushConverter转换它不是问题 -
那你为什么不能把字符串绑定到颜色我的意思是
Background="{Binding ArgbColor }"这样。