我想使用的ObservableCollection从对象数据绑定到XAML视图: 我有具有属性的类:C#WPF的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对象充满了数据,因为我是在监视窗口,如果我指定列表框项目源manualy:
RollList.ItemsSource = ConvertedCollection;
它的工作原理和列表框用数据填充我wan't,但我想要将其绑定到xaml中;
PS。我是C#和WPF的新手。
你的转换器是废话,它使用列表它应该使用列表项目。我复制了你的情况。第一:不要使用Converter,因为它会返回一个新的集合,而不是您的可观察对象。第二@Chris_Eelmaa是对的,使用财产而不是公共领域! –
Samuel