1

像往常一样,我做了一些研究,但在网站或其他地方找不到答案。如果您能指出我现有的问题,我将不胜感激。否则,这是一个问题:

我有一个ListView对象绑定到一个DataTable对象。请参阅以下定义:

<ListView Name="MyList">
        <ListView.View>
            <GridView>
                <GridViewColumn x:Name="Column1Name" DisplayMemberBinding="{Binding Path=Column1}" />
                <GridViewColumn x:Name="Column2Name" DisplayMemberBinding="{Binding Path=Column2}" />
                <GridViewColumn x:Name="Column3Name" DisplayMemberBinding="{Binding Path=Column3}" />
                <GridViewColumn x:Name="Column4Name" DisplayMemberBinding="{Binding Path=Column4}" />
            </GridView>
        </ListView.View>
    </ListView>

绑定代码如下:

DataTable items = new DataTable();
items = DatabaseService.GetMyItems(20, true, items);
Binding binding = new Binding();
binding.Source = items.DefaultView;
binding.Mode = BindingMode.OneWay;
MyList.SetBinding(ListView.ItemsSourceProperty, binding);

执行查询的实际代码如下:

/** Parameters: commandText = <sql>, table = items */    
using (DbConnection connection = new SqlConnection(Project.Properties.Settings.Default.ConnectionString))
        {
            using (DbCommand command = connection.CreateCommand())
            {
                command.CommandText = commandText;
                command.CommandType = CommandType.Text;

                using (DbDataAdapter dataAdapter = new SqlDataAdapter())
                {
                    dataAdapter.SelectCommand = command;
                    dataAdapter.Fill(table);
                }
            }
        }

此代码第一次工作,但是当我GetMyItems在数据更改后再次调用该方法时,数据不会刷新。

我究竟做错了什么?

4

1 回答 1

1

如果它第一次工作是从构造函数工作,一旦加载了你的视图,那么你需要通知你的属性 change

在您的 GetMyItems 方法中使用:

OnPropertyChanged("items");

然后声明方法:

  // Create the OnPropertyChanged method to raise the event 
  protected void OnPropertyChanged(string name)
  {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
          handler(this, new PropertyChangedEventArgs(name));
      }
  }

如果您没有使用预构建的 MVVM 框架从 NotifyPropertyChanged 对象继承以便在 ViewModels 中获取 OnPropertyChanged 方法,这很常见。

在 DataTable 中有一个可观察的属性并不重要,问题在于更改通知。你需要一个ObservableCollection。您可以将 DataTable(DataSet 由一个或多个 DataTable 构造)转换为 ObservableCollection,然后将 ObservableCollection 绑定到 UI 元素

于 2012-09-05T03:13:23.737 回答