【发布时间】: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