3

我正在为主机监控应用程序开发用户界面,该应用程序已经在数据库级别进行监控。我在我的 UI 上显示了 2 个数据网格,它们将在运行时填充。这两个数据网格通过 HostID 连接(HostID 是 LogDatagrid 中的外键)。

第一个数据网格显示主机列表及其状态(正在运行或已停止)。当用户想详细了解状态时,我想显示相应 HostID 的日志状态。当用户在 HostDatagrid 中选择主机 ID 时,如何实现这一点?我添加了我的 XAML 和我的 UI 屏幕截图。

用户界面设计

XAML

 <DataGrid DataContext="{Binding Path=HostData,NotifyOnTargetUpdated=True,Mode=OneWay}" 
    AutoGenerateColumns="False" Name="hostDatagrid" Margin="171,32,235,230">
    <DataGrid.Columns>
    <DataGridTextColumn Header="Host" Width="auto" Binding="{Binding HostID}" />
     <DataGridTextColumn Header="Status" Width="auto" Binding="{Binding HostStatus}"/> 
     </DataGrid.Columns>
  </DataGrid>
 <DataGrid DataContext="{Binding Path=LogData,NotifyOnTargetUpdated=True,Mode=OneWay}"
   AutoGenerateColumns="False" Name="LogDatagrid" Margin="103,108,102,145">
    <DataGrid.Columns>
    <DataGridTextColumn Header="Host ID" Width="auto"  Binding="{Binding HostID}" />
    <DataGridTextColumn Header="Logs" Width="auto"  Binding="{Binding LogID}" />
    <DataGridTextColumn Header="Log Path" Width="auto"  Binding="{Binding LogPath}"/>
    <DataGridTextColumn Header="Date" Width="auto"  Binding="{Binding Date}"/>
    <DataGridTextColumn Header="Last Activity" Width="auto"  Binding="{Binding LastActivity}"/>
  </DataGrid.Columns>

LogFile 模型背后的代码:

    public LogFileModel()
    {

    }
    private int _hostID;
    public int HostID
    {
        get { return _hostID; }
        set { _hostID= value; OnpropertyChanged("HostID"); }
    }

    private string _logid;
    public string LogID
    {
        get { return _logid; }
        set { _logid= value; OnpropertyChanged("LogID"); }
    }

    private string _logpath;
    public string LogPath
    {
        get { return _logPath; }
        set { _logPath = value; OnpropertyChanged("LogPath"); }
    }

    private DateTime _date;
    public DateTime Date;
    {
        get { return _date; }
        set { _date= value; OnpropertyChanged("Date"); }
    }

    private bool _activity;
    public bool LastActivity
    {
        get { return _activity; }
        set { _activity= value; OnpropertyChanged("LastActivity"); }
    }

LogFile ViewModel 背后的代码:

    LogModel _myModel = new LogModel();
    private ObservableCollection<LogFileModel> _logFileData = new  ObservableCollection<LogFileModel>();
    public ObservableCollection<LogFileModel> LogFileData
    {
        get { return _logFileData; }
        set { _logFileData = value; OnPropertyChanged("LogFileData"); }
    }
   public LogFileViewModel()
    {
        initializeload();
        timer.Tick += new EventHandler(timer_Tick);
        timer.Interval = new TimeSpan(0, 0, 3);
        timer.Start();
    }

    ~LogFileViewModel()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                timer.Stop();
                timer.Tick -= new EventHandler(timer_Tick);
            }
            disposed = true;
        }
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        try
        {
            LogFileData.Clear();
            initializeload();
        }
        catch (Exception ex)
        {
            timer.Stop();
            Console.WriteLine(ex.Message);

        }
    }

    private void initializeload()
    {
        try
        {
            DataTable table = _myModel.getData();

            for (int i = 0; i < table.Rows.Count; ++i)
                LogFileData.Add(new LogFileModel
                {
                   HostID= Convert.ToInt32(table.Rows[i][0]),
                   LogID = table.Rows[i][1].ToString(),
                   LogPath = table.Rows[i][2].ToString(),
                   Date = Convert.ToDateTime(table.Rows[i][3]),
                   LastAcivity= table.Rows[i][4].ToString(),                   
                });
        }

        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyname)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyname));
    }

    public class LogModel
    {
        public DataTable getData()
        {
            DataTable ndt = new DataTable();
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
            sqlcon.Open();
            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM [LocalDB].[dbo].[LogFiles]", sqlcon);
            da.Fill(ndt);
            da.Dispose();
            sqlcon.Close();
            return ndt;
        }
    }
}

}

对于主机模型和视图模型,我也遵循了相同的模式。

4

4 回答 4

2

您的代码视图模型中必须包含以下内容

一个 SelectedItem,它将在第一个 DataGrid 中保存所选项目。包含所有主机的集合 HostData。一个空集合 Log Data,它将显示特定主机的日志

//populate with all your hosts and this will bind to your first datagrid
private ObservableCollection<HostModel> _hostData= new ObservableCollection<Host>();

public ObservableCollection<HostModel> HostData
{
    get { return _hostData; }
    set { _hostData= value; OnPropertyChanged("HostData"); }
}

//populate with all the logs for the selected item and bind this to your second datagrid
private ObservableCollection<LogFileModel> _logFileData = new ObservableCollection<LogFileModel>();

public ObservableCollection<LogFileModel> LogFileData
{
    get { return _logFileData; }
    set { _logFileData = value; OnPropertyChanged("LogFileData"); }
}

//when the user selects an item in the first datagrid this property will hold the value
//so you will bind it to the selected item property of your first datagrid
private Host _selectedHost; //initialise to avoid null issues

public HostModelSelectedHost
{
    get{ return _selectedItem; } 
    set 
    {
        //call a method to populate you second collection
        _selectedHost = value;
        logFileData = GetLogsForSelectedHost(_selectedHost);
        OnPropertyChanged("SelectedHost");
    { 
}

//the method for populating your second collection could look like this
private ObservableCollection<LogFileModel> GetLogsForSelectedHost(_selectedHost)
{
    ObservableCollection<LogFileModel> filteredLogs = new ObservableCollection<LogFileModel>;

    filteredLogs = //fill the collection with all the logs that match the host ID of
                   //your selected item
    return filteredLogs ;
}

从您的代码中我不确定哪个类是哪个,但我希望上面的代码可以向您展示这样做的方式。

于 2013-02-05T15:40:19.930 回答
1

做这样的事情:

在您的主数据模型中创建一个名为 search 的方法。Search 有一个查询来搜索您的其他数据库,该数据库保存数据日志并返回数据表。然后为您的主机状态数据网格添加一个 CellClick 侦听器方法,并执行如下操作。我希望我不明白你需要什么。

private void hostDatagrid_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        string cellValue = hostDatagrid[e.ColumnIndex,e.RowIndex].Value.ToString();
        LogFileViewModel logFileViewModel = new LogFileViewModel();
        DataTable table = logFileViewModel.search(cellValue);
        BindingSource bs = new BindingSource();
        bs.DataSource = table;
        logDataGrid.Datasource = table;
        logDataGrid.Update();
        logDataGrid.Refresh();
    }

   // and add this method to  LogFileViewModel



 public DataTable Search(string hostID)
    {
        DataTable ndt = new DataTable();
        SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
        sqlcon.Open();
        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM whatever WHERE hostid ="+hostID, sqlcon);
        da.Fill(ndt);
        da.Dispose();
        sqlcon.Close();
        return ndt;


    }
于 2013-02-05T15:34:42.927 回答
1

1)从您的 ViewModel 中绑定您SelectedItem的属性HostHost DataGrid

SelectedItem = {Binding SelectedHost, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}

2)假设 LogData 是一个 ObservableCollection,在SelectedHost属性的设置器中,更新 LogData 以显示Host.

public Host SelectedHost {
    get;
    set {
        SelectedHost = value;
        UpdateLogData();
        OnPropertyChanged("SelectedHost");
    }
于 2013-02-05T15:47:38.023 回答
0

您必须将所选时间绑定到视图模型中的对象,并且每当此值更改时,您都可以更改集合 LogData 以显示您想要的内容。

于 2013-02-05T15:32:28.170 回答