更新viewmodel时网格不更新

时间:2013-08-27 12:44:38

标签: c# wpf mvvm

我有一个包含服务器列表的网格,当窗口打开时,我请求服务器列表,然后更新viewmodel。但是我的视图模型中没有显示更改。

public ServerInfo_ViewModel serverInfoViewModel { get; set; }

public FindServer2()
{
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(WindowLoaded);
    serverInfoViewModel = new ServerInfo_ViewModel();
}

void WindowLoaded(object sender, RoutedEventArgs e)
{
     Multicast.OnAlarmServerFound += new Multicast.AlarmServerFoundHandler(Multicast_OnAlarmServerFound);
     Multicast.FindAlarmServers();
}

public delegate void Multicast_OnAlarmServerFoundHandler(string IPAddress, string returnvalue);
    void Multicast_OnAlarmServerFound(string IPAddress, string returnvalue)
    {

         ServerInfo si = new ServerInfo();
         si.Server = IPAddress;

         if (source.Length > 1)
              si.Version = source[1];
         if (source.Length > 2)
              si.Connection = source[2];
         if (source.Length > 3)
              si.Port = source[3];
         if (source.Length > 4)
              si.HostName = source[4];
         if (source.Length > 1)
         {
            try
            {
               serverInfoViewModel.Servers.Add(si);   // This is called
            }
            catch
            {}
        }
    }

这是我的viewmodel

    public class ServerInfo_ViewModel : INotifyPropertyChanged
    {
        public ServerInfo_ViewModel()
        {
            this.Servers = new ObservableCollection<ServerInfo>();
            LoadInitialServerList();
        }

        public ObservableCollection<ServerInfo> Servers
        {
            get 
            {
                return servers;
            }
            set
            {
                servers = value;
                servers.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(servers_CollectionChanged); 
            }
        }

        void servers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            // Here you will be informed, if the content of the collection has been changed.  
            OnPropertyChanged("Servers");
        }

        private ObservableCollection<ServerInfo> servers;

        private void LoadInitialServerList()
        {
            servers.Add(new ServerInfo("Test", "Test", "Test", "Test", "Test"));
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion
    }
}

和Xaml

<Window x:Class="Digicom.DESDigitelClientWPF.FindServer2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:Digicom.DESDigitelClientWPF"
>

<Window.DataContext>
    <local:ServerInfo_ViewModel/>
</Window.DataContext>

<StackPanel>
    <DataGrid ItemsSource="{Binding Servers, Mode=TwoWay}" Height="132" Width="442" AutoGenerateColumns="False" GridLinesVisibility="None">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding HostName}" Header="Server"/>
        <DataGridTextColumn Binding="{Binding Server}" Header="IP" />
        <DataGridTextColumn Binding="{Binding Version}" Header="Version" />
        <DataGridTextColumn Binding="{Binding Connection}" Header="Connection" />
        <DataGridTextColumn Binding="{Binding Port}" Header="Port" />
    </DataGrid.Columns>
</DataGrid>
</StackPanel>

当我运行它时,我得到了这个,显示了初始对象,但不是在运行时添加的第二个对象。

enter image description here

1 个答案:

答案 0 :(得分:2)

从XAML文件中删除Datacontext Definition并将其添加到Codebehind中。 您的代码创建了ViewModel的两个实例。您已将ServerInfo添加到未绑定到View的实例,因此无法看到更改。

视图模型

public class ServerInfo_ViewModel : INotifyPropertyChanged
{
    public ServerInfo_ViewModel()
    {
        this.Servers = new ObservableCollection<ServerInfo>();
        LoadInitialServerList();
    }

    public ObservableCollection<ServerInfo> Servers
    {
        get 
        {
            return servers;
        }
        set
        {
            if(servers != value)
            {
                servers = value; 
                OnPropertyChanged("Servers");
            }
        }
    }

    private ObservableCollection<ServerInfo> servers;

    private void LoadInitialServerList()
    {
        servers.Add(new ServerInfo("Test", "Test", "Test", "Test", "Test"));
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
}

}

XAML:

<Window x:Class="Digicom.DESDigitelClientWPF.FindServer2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:Digicom.DESDigitelClientWPF"
>
<StackPanel>
    <DataGrid ItemsSource="{Binding Servers, Mode=TwoWay}" Height="132" Width="442" AutoGenerateColumns="False" GridLinesVisibility="None">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding HostName}" Header="Server"/>
        <DataGridTextColumn Binding="{Binding Server}" Header="IP" />
        <DataGridTextColumn Binding="{Binding Version}" Header="Version" />
        <DataGridTextColumn Binding="{Binding Connection}" Header="Connection" />
        <DataGridTextColumn Binding="{Binding Port}" Header="Port" />
    </DataGrid.Columns>
</DataGrid>
</StackPanel>

代码隐藏:

public ServerInfo_ViewModel serverInfoViewModel { get; set; }

public FindServer2()
{
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(WindowLoaded);
    serverInfoViewModel = new ServerInfo_ViewModel();
    this.DataContext = serverInfoViewModel;

}

void WindowLoaded(object sender, RoutedEventArgs e)
{
     Multicast.OnAlarmServerFound += new Multicast.AlarmServerFoundHandler(Multicast_OnAlarmServerFound);
     Multicast.FindAlarmServers();
}

public delegate void Multicast_OnAlarmServerFoundHandler(string IPAddress, string returnvalue);
    void Multicast_OnAlarmServerFound(string IPAddress, string returnvalue)
    {

         ServerInfo si = new ServerInfo();
         si.Server = IPAddress;

         if (source.Length > 1)
              si.Version = source[1];
         if (source.Length > 2)
              si.Connection = source[2];
         if (source.Length > 3)
              si.Port = source[3];
         if (source.Length > 4)
              si.HostName = source[4];
         if (source.Length > 1)
         {
            try
            {
               serverInfoViewModel.Servers.Add(si);   // This is called
            }
            catch
            {}
        }
    }
相关问题