【问题标题】:IValueConverter Using Lookup Collection使用查找集合的 IValueConverter
【发布时间】: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


【解决方案1】:

这就是我能够开始工作的地方。正如@Darthchai 提到的,我已经在类/窗口中创建了集合。但是,我无法弄清楚如何使用 INotifyPropertyChanged 让特定的 TextBlock 知道进行转换。毕竟我是菜鸟。 :) 我能够做的——我不知道这是否是正确的方法——是使用 TextBlock 的 Loaded 事件来进行转换。这是代码:

        private void BreedTextBlock_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock textBlock = (TextBlock)sender;
            if (textBlock != null && Breeds.Count > 0)
            {
                try
                {
                    short breedID = short.Parse(textBlock.Text);
                    Breed_ breed = Breeds.Single(s => s.BreedID == breedID);
                    textBlock.Text = (string)breed.Breed;
                }
                catch
                {
                }
            }

            return;
        }

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    相关资源
    最近更新 更多