C# 数据绑定ViewModel存在问题
我有一个模型C# 数据绑定ViewModel存在问题,c#,mvvm,C#,Mvvm,我有一个模型 class FontsViewModel : ObservableObject { public FontsViewModel() { InitFonts(); } public ObservableCollection<Typeface> Fonts { get; private set; } protected void InitFonts() {
class FontsViewModel : ObservableObject
{
public FontsViewModel()
{
InitFonts();
}
public ObservableCollection<Typeface> Fonts
{
get;
private set;
}
protected void InitFonts()
{
Fonts = (ObservableCollection<Typeface>)System.Windows.Media.Fonts.SystemFontFamilies;
}
}
我做错了什么?这就像我在上看到的修改版本一样,您无法将SystemFontFamilies转换为ObservableCollection。 而是实例化一个新集合:
Fonts = new ObservableCollection<Typeface> (Fonts.SystemFontFamilies);
编辑:上面的代码在属性类型和集合类型之间不匹配。
请改为使用以下选项之一:
var myFonts = new ObservableCollection<FontFamily>(Fonts.SystemFontFamilies);
var typefaces = new ObservableCollection<Typeface>(Fonts.SystemTypefaces);
两点:
如果字体列表永远不会更改,那么您真的不需要在此处进行ObservableCollection。公开IEnumerable属性就足够了
您确实不应该引用视图特定的对象,如ViewModel中的字体。最好将可用的字体名称公开为字符串,并通过一些服务接口注入可用的名称。视图端的服务接口将调用System.Windows.Media.Fonts.SystemFontFamilies并转换为字符串名称。这为您提供了可测试性隔离,您的单元测试可以提供自己的字体名称
嗯,当我尝试此操作时,我已将字体重命名为AvailableFonts,这样就不会与System.Windows.Media.Fonts冲突,但仍然会出现错误。哦,你说我不能将SystemFontFamilies转换为ObservaleCollection,但我做了一个强制转换?除此之外,ObservaleCollection可以强制转换为IEnumerable,但IEnumerable不能总是强制转换为ObservaleCollection。我说*总是因为不是所有的IEnumerable都是可观察集合,但所有的可观察集合都是IEnumerable。希望这能澄清你的一些问题。我不知道我的方法是否正确,但我尝试使用LINQ通过toString排序和选择字符串,但仍然出现错误。哦,我发现上一个错误是因为字体没有实现IComparable,所以无法对选择进行排序。我将其更改为orderby font.toStringoh,关于2,对于颜色,我应该使用ARGB十六进制值?@jiewmeng,可能;视图模型直接处理颜色是不常见的,对于这种特殊情况,您可能会改变规则。这是因为颜色实际上是模型中的一种数据。为了实现最佳隔离,您可能希望使用独立于视图的字符串,如FFFF0000或Red,但为了清晰起见,我可以看到在整个模型和ViewModel中使用颜色类型的参数。
Fonts = new ObservableCollection<Typeface> (Fonts.SystemFontFamilies);
var myFonts = new ObservableCollection<FontFamily>(Fonts.SystemFontFamilies);
var typefaces = new ObservableCollection<Typeface>(Fonts.SystemTypefaces);