如何更新DataGrid

时间:2019-05-16 08:59:45

标签: c# wpf data-binding datagrid

应用程序的DataContext绑定到我的MainViewModel。此ViewModel具有属性服务和其他一些属性。启动服务时,我想在OnPropertyChanged("Services")StartService()内部调用RefreshServices(),但是它没有更新。

我的XAML / DataGrid:

        <DataGrid x:Name="dataGrid" Grid.Row="2" Grid.ColumnSpan="8"
                  ItemsSource="{Binding Services}"
                  AutoGenerateColumns="False"
                  IsReadOnly="True">

            <DataGrid.Columns>
                <DataGridTextColumn Header="Display Name"  Binding="{Binding DisplayName, Mode=OneWay}"/>
                <DataGridTextColumn Header="Status" Binding="{Binding Status, Mode=OneWay}" />
                <DataGridTextColumn Header="Machine Name" Binding="{Binding MachineName, Mode=OneWay }" />
                <DataGridTextColumn Header="Can Stop" Binding="{Binding CanStop, Mode=OneWay}" />
            </DataGrid.Columns>
        </DataGrid>

我的ViewModel:

namespace ServiceStarterPRAT.ViewModels
{
    public class MainViewModel : ObservableObject
    {
        #region Services Properties
        private ObservableCollection<ServiceController> _services;
        private ObservableCollection<ServiceController> _selectedServices;

        public ObservableCollection<ServiceController> SelectedServices
        {
            get
            {
                return _selectedServices;
            }
            set
            {
                if (_selectedServices == null) return;
                _selectedServices = value;
                OnPropertyChanged("SelectedServices");
            }
        }
        public ObservableCollection<ServiceController> Services
        {
            get
            {
                _services.Clear();
                var curenntServices = Utils.UpdateServices(ComputerNames);
                foreach (var service in curenntServices)
                    if (service.MachineName == SelectedComputer)
                        if (Utils.CustomerNameOf(service) == SelectedCustomer)
                            _services.Add(service);
                return _services;
            }
            set
            {
                //if (_services == null) return;
                _services = value;
                OnPropertyChanged("Services");
                OnPropertyChanged("SelectedServices");
            }
        }

        #endregion

我认为我还没有完全理解OnPropertyChanged()。我想,每当我调用OnPropertyChanged("Services")之类的东西时,绑定到服务属性的任何内容都会得到通知并获取更新的数据。但是,这不是..我在做什么错。除了我的XAML之外,您还需要哪些信息?

1 个答案:

答案 0 :(得分:1)

您应该更改的一件事是

        set
        {
            if (_selectedServices == null) return;
            _selectedServices = value;
            OnPropertyChanged("SelectedServices");
        }

_selectedServices最初为null,并将保持不变。 设置它总是会失败,因为它总是会返回。

顺便说一句,我建议您也总是使用花括号。始终将您的声明放在下一行。

  if (_selectedServices == null) 
     {
         // this is a terrible idea because it will always be true and your setter stops the property being set
          return;
     }