【问题标题】:C# wpf observablecollection binding to xamlC# wpf observablecollection 绑定到 xaml
【发布时间】:2015-01-02 18:01:59
【问题描述】:

我正在尝试使用 ObservableCollection 将数据从对象绑定到 xaml 视图: 我有一个具有属性的类:

public ObservableCollection<Roll> RollList = new ObservableCollection<Roll>();

还有一些修改该集合的方法(基本上是添加新条目的方法),如下所示:

RollList.Add(roll); //roll is and Roll class object bellow

这是我在集合中使用的一个滚动类:

class Roll : INotifyPropertyChanged
{
    private List<int> _hitList;

    public List<int> HitList
    {
        get { return _hitList; }
        set { _hitList = value; OnPropertyChanged("HitList"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

public class ListToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        List<int> list = value as List<int>;
        return String.Join("", list.ToArray());
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string list = value as string;
        return list.Split(' ').Select(n => int.Parse(n)).ToList();
    }
}

现在在我的主窗口类中,我实例化我的类,该类在上面构造 ObservableCollection 对象并用数据填充它;

我像这样将我的集合绑定到 DataContex;

DataContext = MyCoolClass; //MyCoolClass has ObservableCollection<Roll> RollList inside of it

我做的最后一件事:

<Window.Resources>
    <local:ListToStringConverter x:Key="ListToStringConverter" />
</Window.Resources>

<ListBox 
    Height="Auto" 
    Width="Auto" 
    Name="RollList" 
    ItemsSource="{Binding RollList, Converter={StaticResource ListToStringConverter}}"
/>

在列表框中没有填充数据。我知道 RollList 对象充满了数据,因为我可以在监视窗口中,如果我手动分配列表框项目源:

RollList.ItemsSource = ConvertedCollection;

它可以工作并且列表框填充了我不想要的数据,但我想将它绑定到 xaml 中;

PS。我是 C# 和 WPF 的新手。

【问题讨论】:

  • 你的转换器是垃圾,它使用 List 它应该使用一个滚动项目列表。我复制了你的案例。第一:不要使用 Converter,因为它返回一个新集合而不是你的 observable。第二个@Chris_Eelmaa 是对的,使用属性而不是公共字段!

标签: c# wpf xaml observablecollection


【解决方案1】:
public ObservableCollection<Roll> RollList = new ObservableCollection<Roll>();

这不是属性。那是一个领域。 WPF 使用属性。

【讨论】:

  • 我看我还不太明白这个概念,据我所知,属性应该有get、set方法?
  • @sepikas_antanas:是的。
【解决方案2】:

您需要实现一个属性。

public MyCoolClass
{
    private ObservableCollection<Roll> _rollList;

    public ObservableCollection<Roll> RollList
    {
        get { return _rollList; }
        set
        {
            if (_rollList != value)
            {
                _rollList = value;
                OnPropertyChanged("RollList");
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2011-02-05
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 2013-10-14
    • 2013-04-18
    相关资源
    最近更新 更多