【问题标题】:set xaml code ItemsSource="{Binding}" with code behind使用后面的代码设置 xaml 代码 ItemsSource="{Binding}"
【发布时间】:2012-03-30 07:57:30
【问题描述】:

我有以下属性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# 填充列表视图时,列表视图不会被填充。我做错了什么?

【问题讨论】:

    标签: c# datacontext inotifypropertychanged itemssource


    【解决方案1】:

    您必须设置 Binding 实例的一些属性。在您的情况下,它可能类似于...

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

    【讨论】:

      【解决方案2】:

      您需要创建一个Binding 对象。

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

      传递给构造函数的参数是您在 XAML 绑定中习惯使用的 Path。

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

      【讨论】:

        【解决方案3】:
        listView1.SetBinding(ListView.ItemsSourceProperty, new Binding());
        

        【讨论】:

          猜你喜欢
          • 2018-07-03
          • 1970-01-01
          • 2011-12-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多