首页 > 解决方案 > 转换 DataGrid 中的项

问题描述

我有一个所有存在的项目的“主列表”。然后,我有一个类(称为 Inventory),负责跟踪那里有多少物品,数量可以是任何整数。

我的 DataGrid 绑定到主列表,然后一个特定的列负责显示库存中的项目数量。Inventory 类是一个 IValueConverter。

我的想法是使用 Inventory 类将 Item 从 DataGrid 转换为 int(我拥有的项目数量)。

XAML:

<UserControl>

    <UserControl.Resources>
        <converters:Inventory x:Key="FindQuantity"/>
    </UserControl.Resources>

              
    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding MasterList}"> <!-- Binding to the master List -->
        <DataGrid.Columns>

            <DataGridTemplateColumn Header="Quantity">
                <DataGridTemplateColumn.CellTemplate>

                    <DataTemplate>
                        <!-- Converting: -->
                        <TextBlock Text="{Binding Converter={StaticResource FindQuantity}}"/>
                    </DataTemplate>

                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>
    </DataGrid>
</UserControl>

清单脚本的一部分:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
  var item = (Item)value; //<------------Here's where the Debug points the error
  return HowMany(item);
}

public int HowMany(Item item)
{
  if (storage.ContainsKey(item))
    return storage[item];
  else return 0;
}

我得到的错误:

System.InvalidCastException:'无法将'MS.Internal.NamedObject'类型的对象转换为'Playfield2_WPF.Objetos.Item'。

我是 WPF 新手,所以我不完全了解绑定。我的错误在哪里?我的绑定工作方式有问题还是问题出在其他地方?谢谢。

编辑:
这是“MasterList”的代码(它是 ObservableObject 的列表,一个实现 INotifyPropertyChanged 的​​类。源代码:https ://pastebin.com/wZiis6rF )


public class Inventary : ObservableObject, IValueConverter
{       
  private List<Item> _masterList;
  public List<Item> MasterList
    {
        get { return _masterList; }
        set
        {
          //this method is from the ObservableObjet class
          //It basically calls PropertyChanged from the INotifyPropertyChanged interface
            OnPropertyChanged(ref _masterList, value, nameof(MasterList)); 
        }
    }

}
   //Item is basically some int and string propierties
    public class Item : ObservableObject 
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                OnPropertyChanged(ref _name, value, nameof(Name));
            }
        }

        private decimal _cost;
        public decimal Cost
        {
            get { return _cost; }
            set
            {
                OnPropertyChanged(ref _cost, value, nameof(Cost));
            }
        }

    }


标签: c#wpfxaml

解决方案


以下是转换器的两个示例

一:绑定到其他元素控件

<RadioButton  IsChecked="False" x:Name="targetradiobutton"/>
<!-- Below is a textbox that will show/hide depends on radiobutton's isChecked state!-->
<TextBlock Visibility="{Binding IsChecked, ElementName="targetradiobutton", Converter={StaticResource BooleanToVisibilityConverter}}"/>

二:绑定到后端变量

在 test.xaml.cs

Public Test(){ this.DataContext = this;} //one of a way to bind to backend class. there's other way too
Public bool IsVisible{ get; set;}

在 test.xaml

<!--Converting backned boolean to visibility.
<TextBlock Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}"/>

转换器示例:

public class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool)
            {
                return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

在您的情况下,当您使用默认绑定时,您将 Textbox 的 Text 绑定到转换器。因此,您可以基于上面的示例并绑定到包含您想要的目标 Item 的变量/其他元素。

  <!-- Converting: -->
  <TextBlock Text="{Binding TargetItem, Converter={StaticResource FindQuantity}}"/>

推荐阅读