【发布时间】:2020-06-24 22:31:55
【问题描述】:
我正在使用这样的转换器:
public class BreedConverter : IValueConverter
{
static ObservableCollection<Breed_> Breeds = Breed_.GetBreeds();
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && Breeds.Count > 0)
{
short breedID = (short)value;
Breed_ breed = Breeds.Single(s => s.BreedID == breedID);
return (string)breed.Breed;
}
else
return "";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
从 SQL Server 数据库中检索 Breeds 集合。我想检索一次,然后用它来进行转换。我不想每次需要转换时都去数据库。
有没有更好的方法来做到这一点,例如ResourceDictionary(我不知道如何在这种情况下使用它,因为我还是个菜鸟)?
【问题讨论】:
-
我不认为在这种情况下你真的需要 IValueConverter。在您的主类/窗口中,我建议您在那里创建您的可观察集合,并且只创建一次。然后你可以使用 INotifyPropertyChange 进行转换,传回你想要的品种。
-
我不知道该怎么做。我是菜鸟。 TreeView 中会有一堆品种 ID。我只想将品种 ID 转换为品种名称。
-
将您的集合移动到 DataContext 类,例如
ViewModel。然后使用 MultiBinding 和IMultiValueConverter在此处传递:ID 和 Collection。 -
我不确定你的意思。
标签: c# wpf converters ivalueconverter