【问题标题】:How can I bind label content with value from query?如何将标签内容与查询中的值绑定?
【发布时间】:2020-02-23 02:04:40
【问题描述】:

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

<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
    <Label Content="Date:" FontSize="10" />
    <Label x:Name="HomeScreenLabelInfoDate" FontSize="10" FontWeight="DemiBold" FontStyle="Italic" Content="{Binding InfoDate}"/>
    <Label Content="-"/>
    <Label Content="Author:" FontSize="10"/>
    <Label x:Name="HomeScreenLabelInfoAuthor" Margin="3 0" FontSize="10" FontWeight="DemiBold" FontStyle="Italic" Content="{Binding InfoAuthor}"/>
</StackPanel>

这是我的代码隐藏:

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

【问题讨论】:

标签: c# wpf xaml mvvm data-binding


【解决方案1】:

对您的代码进行以下更改。

  1. 使 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;
    }
    
  2. 在用户控件的代码隐藏(构造函数)中进行以下更改,

    public HomeUserControl()
    {
        InitializeComponent();
    
        try
        {
            var newsData = GetPublications(); 
            this.DataContext = newsData;
        }
        catch (Exception ex)
        {
    
            MessageBox.Show(ex.Message);
        }
    }
    
  3. 为 NewsData 类实现 INotifyPropertyChanged。请参阅下面的链接了解如何实现此目标

https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-property-change-notification

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

试一试,如果您还有任何问题,请告诉我们。

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

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

  1. 在您的 .xaml 中,您使用“InfoDate”和“InfoAuthor”绑定到您的标签。 但是您的 NewsData 没有这些属性。

您的 NewsData 属性名称是“InfotAuthor”和“InfotDate” - 其中包含“t”

  1. 我已使用您的 xaml 代码(在进行上述更改后)。

没有 INotifyPropertyChanged 继承,我可以看到数据。我想如果您进行上述更改,那么您应该能够在视图中看到数据。

  1. 如果你想实现 INotifyPropertyChanged,你可以按照如下,

    公共类 NewsData : INotifyPropertyChanged { 私有字符串_title;

    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;
    

    }

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

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

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

Date = InfotDate;

你需要设置为"Date = value;"

希望您能理解我更新后的答案的不同之处。

尝试一下,如果您还有其他问题,请告诉我们。

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

【讨论】:

  • 嗨 G K,Notify 属性让我更难以实现,主要是因为我对 mvvm 不是很熟悉。我已经用新代码更新了问题
  • 您好,更改后您可以显示数据。您的 NewsData 中的某些属性也错误地映射到后端字段。请参阅 InfotTitle 和 InfotMesaage。你面临什么错误? DataContext 是有助于减少绑定到 UI 和从 UI 绑定到 ViewModel 的大量代码的功能。
  • 您好,更改后您可以显示数据。您的 NewsData 中的某些属性也错误地映射到后端字段。请参阅 InfotTitle 和 InfotMesaage。你面临什么错误? DataContext 是有助于减少绑定到 UI 和从 UI 绑定到 ViewModel 的大量代码的功能。
  • 返回 newsData 时出现错误; => 在当前上下文中不存在
  • 那是因为您在 GetPublications() 方法中缺少此语句“NewsData newsData = new NewsData();”。见 connStr 语句后。
猜你喜欢
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多