Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将标签内容与查询中的值绑定?_C#_Wpf_Xaml_Mvvm_Data Binding - Fatal编程技术网

C# 如何将标签内容与查询中的值绑定?

C# 如何将标签内容与查询中的值绑定?,c#,wpf,xaml,mvvm,data-binding,C#,Wpf,Xaml,Mvvm,Data Binding,我试图根据运行存储过程得到的结果绑定标签的内容。这是我的XAML: 下面是我的代码: public HomeUserControl() { InitializeComponent(); try { GetPublications(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } public class NewsData {

我试图根据运行存储过程得到的结果绑定标签的内容。这是我的XAML:


下面是我的代码:

public HomeUserControl()
{
    InitializeComponent();

    try
    {
        GetPublications();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

public class NewsData
{
    public string InfoTitle { get; set; }

    public string InfoMessage { get; set; }

    public string InfoDate { get; set; }

    public string InfoAuthor { get; set; }
}

public void GetPublications()
{
    string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;

    using (var Connect = new SqlConnection(connstr))
    {
        Connect.Open();
        using (var Command = new SqlCommand("[dbo].[spNewsManagementTb_DisplayNews]", Connect))
        {
            Command.CommandType = CommandType.StoredProcedure;
            Command.Parameters.Add("@entity_id", SqlDbType.VarChar).Value = LoggedInData.LoggedInstitutionId;
            SqlDataReader dr = Command.ExecuteReader();
            while (dr.Read())
            {
                string newsTitle = dr.GetString(0);
                string newsMessage = dr.GetString(1);
                string newsAuthor = dr.GetString(2);
                DateTime newsDate = dr.GetDateTime(3);
                string newsDateFormated = newsDate.ToString("dddd, dd MMMM yyyy");

                NewsData newsData = new NewsData();
                newsData.InfoTitle = newsTitle;
                newsData.InfoDate = newsDateFormated;
                newsData.InfoAuthor = newsAuthor; 

            }

            dr.Close();
            Connect.Close();
        }
    }
}
无论何时运行应用程序,我都不会在GUI上看到任何数据。我已经能够通过直接从查询读取的值中分配标签的值来克服这一问题,但我希望在整个代码中继续使用数据绑定以保持一致性,但事实证明这一点很难实现

编辑

我想说的是,我是一名编程初学者,因此我并不擅长理解所有概念,但INotifyPropertyChanged属性引发了多个错误。以下是包含Notify属性后的代码:

public HomeUserControl()
{
    InitializeComponent();

    try
    {
        var newsData = GetPublications();
        this.DataContext = newsData;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

public NewsData : INotifyPropertyChanged
{
    private string Title;

        private string Message;

        private string Date;

        private string Author;

        public event PropertyChangedEventHandler PropertyChanged;

        public NewsData(string infoTitle, string infoMessage, string infoDate, string infoAuthor)
        {
            this.Author = infoAuthor;
            this.Date = infoDate;
            this.Message = infoMessage;
            this.Title = infoTitle;
        }

        public string InfotAuthor
        {
            get { return Author; }

            set
            {
                Author = InfotAuthor;
                OnPropertyChanged();
            }
        }

        public string InfotDate
        {
            get { return Date; }

            set
            {
                Date = InfotDate;
                OnPropertyChanged();
            }
        }

        public string InfotMessage
        {
            get { return Message; }

            set
            {
                Author = InfotMessage;
                OnPropertyChanged();
            }
        }

        public string InfotTitle
        {
            get { return Title; }

            set
            {
                Author = InfotTitle;
                OnPropertyChanged();
            }
        }

        protected void OnPropertyChanged(string Author = null, string Message = null, string Date = null, string Title = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Author));

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Message));

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Date));

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Title));
        }
}

public NewsData GetPublications()
{
    string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;

    using (var Connect = new SqlConnection(connstr))
    {
        Connect.Open();
        using (var Command = new SqlCommand("[dbo].[spNewsManagementTb_DisplayNews]", Connect))
        {
            Command.CommandType = CommandType.StoredProcedure;
            Command.Parameters.Add("@entity_id", SqlDbType.VarChar).Value = LoggedInData.LoggedInstitutionId;
            SqlDataReader dr = Command.ExecuteReader();
            while (dr.Read())
            {
                string newsTitle = dr.GetString(0);
                string newsMessage = dr.GetString(1);
                string newsAuthor = dr.GetString(2);
                DateTime newsDate = dr.GetDateTime(3);
                string newsDateFormated = newsDate.ToString("dddd, dd MMMM yyyy");

                NewsData newsData = new NewsData();
                newsData.InfoTitle = newsTitle;
                newsData.InfoDate = newsDateFormated;
                newsData.InfoAuthor = newsAuthor; 

            }

            dr.Close();
            Connect.Close();
        }
    }

 return newsData;
}

错误是由GetPublications()方法引起的,该方法无法识别NewsData,请对代码进行以下更改

  • 使GetPublications()返回“NewsData”类型,如下所示

    public NewsData GetPublications()
    {
        string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NewsData newsData = new NewsData();
    
        using (var Connect = new SqlConnection(connstr))
        {
            Connect.Open();
            using (var Command = new SqlCommand("[dbo].[spNewsManagementTb_DisplayNews]", Connect))
            {
                Command.CommandType = CommandType.StoredProcedure;
                Command.Parameters.Add("@entity_id", SqlDbType.VarChar).Value = LoggedInData.LoggedInstitutionId;
                SqlDataReader dr = Command.ExecuteReader();
                while (dr.Read())
                {
                    string newsTitle = dr.GetString(0);
                    string newsMessage = dr.GetString(1);
                    string newsAuthor = dr.GetString(2);
                    DateTime newsDate = dr.GetDateTime(3);
                    string newsDateFormated = newsDate.ToString("dddd, dd MMMM yyyy");
    
    
                    newsData.InfoTitle = newsTitle;
                    newsData.InfoDate = newsDateFormated;
                    newsData.InfoAuthor = newsAuthor; 
    
                }
    
                dr.Close();
                Connect.Close();
            }
        }
    
        return newsData;
    }
    
  • 在用户控件的代码隐藏(构造函数)中,执行以下更改:

    public HomeUserControl()
    {
        InitializeComponent();
    
        try
        {
            var newsData = GetPublications(); 
            this.DataContext = newsData;
        }
        catch (Exception ex)
        {
    
            MessageBox.Show(ex.Message);
        }
    }
    
  • 为NewsData类实现INotifyPropertyChanged。有关如何实现这一点,请参见下面的链接

  • 小建议:-我更喜欢以异步方式进行数据库调用,以便我的用户控件加载并等待数据来绑定

    如果您还有任何问题,请尝试并告知我们

    编辑:--在更新问题后添加了额外的代码

    嗨, 我从你的代码中看到了一些错误

  • 在.xaml中,您使用“InfoDate”和“InfoAuthor”绑定到标签的。 但是您的NewsData没有这些属性
  • 您的NewsData属性名称是“InfotAuthor”和“InfotDate”-其中有“t”

  • 我已经使用了您的xaml代码(在做了上述更改之后)
  • 如果没有INotifyPropertyChanged继承,我就能够看到数据。我想如果你做了以上的修改,那么你应该能够在你的视图中看到数据

  • 如果要实现INotifyPropertyChanged,可以按照以下步骤操作:

    公共类NewsData:INotifyPropertyChanged { 私有字符串\u标题

    private string _message;
    
    private string _date;
    
    private string _author;
    
    public string InfoAuthor
    {
        get { return _author; }
    
        set
        {
            _author = value;
            OnPropertyChanged("InfoAuthor");
        }
    }
    
    public string InfoDate
    {
        get { return _date; }
    
        set
        {
            _date = value;
            OnPropertyChanged("InfoDate");
        }
    }
    
    public string InfoMessage
    {
        get { return _message; }
    
        set
        {
            _message = value;
            OnPropertyChanged("InfoMessage");
        }
    }
    
    public string InfoTitle
    {
        get { return _title; }
    
        set
        {
            _title = value;
            OnPropertyChanged("InfoTitle");
        }
    }
    
    protected void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    
    public event PropertyChangedEventHandler PropertyChanged;
    
    }

  • 我已经让私有成员以带驼峰式大小写的“\u1”开头(这只是后端字段的正确命名约定)

    我已经实现了OnPropertyChanged()方法,并且正在从每个属性设置器方法调用

    在setter方法中,您试图设置如下,这是错误的

    您需要设置为“日期=值;”

    希望你能从我更新的答案中理解其中的差异

    如果您还有任何其他问题,请尝试并告知我们


    如果它回答了您的问题,请接受它作为答案。

    NewsData需要支持。Hi G K,Notify属性使我更难实现,主要是因为我对mvvm不太熟悉。我已经用新的代码更新了这个问题,修改后你能显示数据吗。此外,NewsData中的某些属性与后端字段映射错误。请参阅Infottle和InfotMesage。你面临着什么样的错误?DataContext是一项功能,它有助于减少从UI绑定到ViewModel和从UI绑定到ViewModel的大量代码。您好,更改后,您就可以显示数据了。此外,NewsData中的某些属性与后端字段映射错误。请参阅Infottle和InfotMesage。你面临着什么样的错误?DataContext是有助于减少绑定到您的ViewModel的UI和从UI到ViewModel的大量代码的功能。我在返回newsData时遇到一个错误;=>当前上下文中不存在,这是因为GetPublications()方法中缺少此语句“NewsData NewsData=new NewsData();”。参见后面的connStr语句。
    Date = InfotDate;