DataGrid绑定到ObservableCollection

时间:2016-05-17 15:26:10

标签: c# wpf data-binding datagrid observablecollection

我正在尝试将ViewModel上的ObservableCollection绑定到我视图上的DataGrid:

public class RequestListViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Request> requests;
    private Timer uTimer;
    public RequestListViewModel()
    {
        requests = RequestAction.getRequestList();
        SetRequestsUpdateTimer();
    }

    public ObservableCollection<Request> Requests
    {
        get { return requests; }
        set { requests = value; OnPropertyChanged("Requests"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

使用计时器更新此ObservableCollection并且工作正常。数据已更新。问题是更新没有反映在视图方面:

<DataGrid Name="lstRequests" AutoGenerateColumns="False" IsReadOnly="True" GridLinesVisibility="None" MouseDoubleClick ="myDataGrid_MouseDoubleClick" 
                  >
            <DataGrid.Columns>
...

            </DataGrid.Columns>

我创建了这样的绑定:

public RequestListView()
{
    InitializeComponent();
    model = new RequestListViewModel();
    //this.DataContext = model;
    lstRequests.ItemsSource = model.Requests;
    Binding myBinding = new Binding();
    myBinding.Source = model;
    myBinding.Path = new PropertyPath("Requests");
    myBinding.Mode = BindingMode.TwoWay;
    myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    lstRequests.SetBinding(DataGrid.ItemsSourceProperty, myBinding);
}

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

只会在代码中设置char *from_setlocale = setlocale(LC_ALL, "en_IE.UTF-8"); char *checked_setlocale = setlocale(LC_ALL, NULL); std::cout << (from_setlocale ? from_setlocale : "NULL") << std::endl << (checked_setlocale ? checked_setlocale : "NULL") << std::endl;

DataContext
this.DataContext = model;

<DataGrid ItemsSource="{Binding Requests}" ... /> TwoWay是无意义的,不适用于UpdateSourceTrigger。如果您更改层次结构中的ItemsSource,则此绑定当然会失败。此外,如果您完全切换模型并且不更新DataContext,则绑定也将不再更新。

从评论中可以清楚地看出,您的问题是您滥用了代码。通常我会在DataContext使用ObeservableCollections时通过将其设为只读和仅限来防止这种情况:

private readonly ObeservableCollection<...> _field = new ObeservableCollection<...>();
public ObeservableCollection<...> Property { get { return _field; } }