C#wpf observablecollection绑定到xaml

ant*_*kas 0 c# wpf xaml observablecollection

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

public ObservableCollection<Roll> RollList = new ObservableCollection<Roll>();
Run Code Online (Sandbox Code Playgroud)

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

RollList.Add(roll); //roll is and Roll class object bellow
Run Code Online (Sandbox Code Playgroud)

这是我在集合中使用的roll类:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

DataContext = MyCoolClass; //MyCoolClass has ObservableCollection<Roll> RollList inside of it
Run Code Online (Sandbox Code Playgroud)

我做的最后一件事:

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

<ListBox 
    Height="Auto" 
    Width="Auto" 
    Name="RollList" 
    ItemsSource="{Binding RollList, Converter={StaticResource ListToStringConverter}}"
/>
Run Code Online (Sandbox Code Playgroud)

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

RollList.ItemsSource = ConvertedCollection;
Run Code Online (Sandbox Code Playgroud)

它工作,列表框填充了我不想的数据,但我想在xaml中绑定它;

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

Ert*_*maa 7

public ObservableCollection<Roll> RollList = new ObservableCollection<Roll>();
Run Code Online (Sandbox Code Playgroud)

那不是财产.那是一个领域.WPF使用属性.