简体   繁体   English

WPF Datagrid无法更新

[英]WPF Datagrid does not update

I have a (most probably) very simple question for you regarding a WPF Datagrid that I bound to a ObservableCollection and that unfortunately does not update when I add items to this Collection. 关于我绑定到ObservableCollection的WPF Datagrid,我有一个(最可能是)一个非常简单的问题,很遗憾,当我向该Collection中添加项目时,它并没有更新。

This is my View incl. 这是我的观点。 the Datagrid: Datagrid:

<UserControl.Resources>
    <local:SinglePackTransactions_ViewModel x:Key="vm"/>
</UserControl.Resources>
...
...
...
    <DataGrid x:Name="DataGridRequestPacks_SinglePack" AutoGenerateColumns="False" Grid.Row="1" Width="700" Margin="30"
                      ItemsSource="{Binding SinglePackResultList, Source={StaticResource vm}}" IsReadOnly="True">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Created" Width="Auto" Binding="{Binding Created}"/>
            <DataGridTextColumn Header="Product Code" Width="Auto" Binding="{Binding ProductCode}"/>
        </DataGrid.Columns>
    </DataGrid>

When I click on a button (Command="SendRequestCmd") I add a an item of my custom class ("Pack") to my ObservableCollection SinglePackResultList. 当我单击按钮(Command =“ SendRequestCmd”)时,我向我的ObservableCollection SinglePackResultList添加了一个自定义类的项目(“ Pack”)。 In the constructor of my ViewModel I have this here: 在我的ViewModel的构造函数中,我在这里:

SinglePackResultList = new ObservableCollection<Pack>();

SendRequestCmd = new RelayCommand((object z) =>
{
    try
    {
        SinglePackResultList.Add(SOAPRequest.SOAPRequestHandler(new Pack() {Created = (DateTime.Now).ToShortDateString(), ProductCode = ProductCode_SinglePack, BatchID = BatchID_SinglePack, BatchExpiry = BatchExpiry_SinglePack, PackSerialnumber = SerialNumber_SinglePack, PackTransaction = Transaction_SinglePack.TransactionID }));
    }
    catch (Exception)
    {
        return;
    }
},
CanExecute);

When I set a debug point, I can see that after every button-click there is on additional item in my ObservableCollection SinglePackResultList - so this works. 当我设置调试点时,我可以看到每次单击按钮后,ObservableCollection SinglePackResultList中都有其他项-这样就可以了。 But unfortunately the Datagrid stays empty. 但是不幸的是,Datagrid仍然是空的。 I tried to add a NotifyPropertyChanged("SinglePackResultList") directly after the SinglePackResultList.Add(...) , but this did not work as well. 我试图在SinglePackResultList.Add(...)之后直接添加一个NotifyPropertyChanged("SinglePackResultList") SinglePackResultList.Add(...) ,但是效果不佳。

I'm totally lost how I can get this working. 我完全迷失了如何使它工作。 :-( :-(

Two ways to deal with data binding in WPF. 在WPF中处理数据绑定的两种方法。

Create in constructor and never change it. 在构造函数中创建,永远不要更改它。 For example 例如

public class A{
    public ObservableCollection<int> ObserableList { get; set; }

    public A() { ObservableList = new ObservableCollection<int>(); }
}

then you only add or remove elements in collection. 那么您只能添加或删除集合中的元素。

Or you can use full property and event PropertyChanged, in this way you can assign another collection to it. 或者,您可以使用完整属性和事件PropertyChanged,以这种方式可以为其分配另一个集合。

public class A {
    private ObservableCollection<int> observableList;

    public ObservableCollection<int> ObservableList
    {
        get { return observableList; }
        set
        {
            observableList = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ObservableList));
        }

    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void Init() 
    {
        ObservableList = new ObservableCollection<int>();
    }
}

based on your feedback, I could identify my mistake. 根据您的反馈,我可以确定我的错误。 I forgot to set the DataContext of my ViewModel and I removed the staticresource. 我忘了设置ViewModel的DataContext并删除了staticresource。

So here is what works for me - maybe this will also help others: 所以这对我有用-也许这也会对其他人有所帮助:

View-XAML: 查看-XAML:

<DataGrid x:Name="DataGridRequestPacks_SinglePack" AutoGenerateColumns="False" Grid.Row="1" Width="1150" Margin="30" ItemsSource="{Binding SinglePackResultList}" IsReadOnly="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Created" Width="Auto" Binding="{Binding Created}"/>
        <DataGridTextColumn Header="Product Code" Width="Auto" Binding="{Binding ProductCode}"/>
    </DataGrid.Columns>
</DataGrid>

View.cs (Constructor): View.cs(构造函数):

public SinglePackTransactions_View()
{
    InitializeComponent();
    this.DataContext = new SinglePackTransactions_ViewModel();
}

In my ViewModel I just used the ObservableSollection as a property: 在我的ViewModel中,我只是将ObservableSollection用作属性:

public ObservableCollection<Pack> SinglePackResultList { get; set; }

In the constructor of my ViewModel I used the bound ICommand-Button to add items to my ObservableCollection: 在ViewModel的构造函数中,我使用了绑定的ICommand-Button将项添加到ObservableCollection中:

SinglePackResultList = new ObservableCollection<Pack>();

SendRequestCmd = new RelayCommand((object z) =>
{
    try
    {
        SinglePackResultList.Add(
            SOAPRequest.SOAPRequestHandler(
                new Pack()
                {
                    ProductCode = ProductCode_SinglePack,
                    BatchID = BatchID_SinglePack,
                    BatchExpiry = BatchExpiry_SinglePack,
                    PackSerialnumber = SerialNumber_SinglePack,
                    PackTransaction = Transaction_SinglePack.TransactionID
                }
            )
        );
    }
    catch (Exception e)
    {
        return;
    }
},
CanExecute);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM