设置xaml代码ItemsSource=“;{绑定}”;后面有代码

本文关键字:代码 绑定 ItemsSource 设置 xaml | 更新日期: 2023-09-27 18:27:46

我有以下属性Temp2:(我的UserControl实现INotifyPropertyChanged)

    ObservableCollection<Person> _Temp2;
    public ObservableCollection<Person> Temp2
    {
        get
        { 
            return _Temp2; 
        }
        set
        {
            _Temp2 = value;
            OnPropertyChanged("Temp2");
        }
    }
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

我需要动态创建一个列表视图。我在XAML中有以下列表视图:

<ListView 
     Name="listView1" 
     DataContext="{Binding Temp2}" 
     ItemsSource="{Binding}" 
     IsSynchronizedWithCurrentItem="True">
 <ListView.View>
 .... etc

现在我正试图用c#创建相同的列表视图,如下所示:

        ListView listView1 = new ListView();
        listView1.DataContext = Temp2;
        listView1.ItemsSource = Temp2; // new Binding(); // ????? how do I have to implement this line
        listView1.IsSynchronizedWithCurrentItem = true;
        //.. etc

当我用C#填充列表视图时,列表视图不会被填充。我做错了什么?

设置xaml代码ItemsSource=“;{绑定}”;后面有代码

您需要创建一个Binding对象。

Binding b = new Binding( "Temp2" ) {
    Source = this
};
listView1.SetBinding( ListView.ItemsSourceProperty, b );

传递给构造函数的参数是用于XAML绑定的Path

如果像上面那样将DataContext设置为Temp2,则可以省略PathSource,但我个人认为绑定到ViewModel(或其他数据源)并使用Path比直接绑定到类成员更可取。

您必须设置Binding实例的一些属性。在你的情况下,可能会是。。。

listView1.SetBinding(ListView.ItemsSourceProperty, new Binding { Source = Temp2 });
listView1.SetBinding(ListView.ItemsSourceProperty, new Binding());