在 UserControl 中绑定文本块

Binding Textblock in UserControl

我正在学习 WPF 和 C#,我正在尝试在用户控件中进行文本块绑定。

我有classSeller.cs

  public class SellerInfo
    {
        public string Name { get; set; }
        public string ID { get; set; }
        public float workTime { get; set; }
        public float loginTime { get; set; }
        public int soldTickets { get; set; }
        public int ticketReservation { get; set; }
        public float totalAmountP { get; set; }
    }

我想通过

从数据库中获取数据
 public void accountInfo()
    {
        con = new SqlConnection(@"Data Source=DESKTOP-8T7J7IH;Initial Catalog=Db1234;Integrated Security=True");
        con.Open();
        string s1 = @"SELECT Name +' ' + Surname FROM Seller WHERE LoginUser = '12345'";
        cmd = new SqlCommand(s1, con);
        SqlDataReader rd = cmd.ExecuteReader();
        do
        {
            while (rd.Read())
            {
                {
                    SellerInfo item = new SellerInfo();
                    item.Name = rd.GetString(0);

                };
            }
        }
        while (rd.NextResult());
        rd.Close();

    }

在上面的示例中只有名称,现在我想知道如何将我得到的内容绑定到文本块并在用户控件中显示它?

我创建了类似的东西:

<TextBlock x:Name="sellerName" HorizontalAlignment="Left" Margin="112,20,0,0" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" Width="166"/>

并阅读它,在 UserControl 中我应该使用 DataContext="{Binding RelativeSource={RelativeSource Self}}" 后来我尝试设置 DataContext=this; 但它仍然没有结果。我读了很多关于它的文章,但我不知道如何在这个例子中得到它。

提前致谢

你实现了INotifyPropertyChanged接口了吗?

您应该稍微了解一下 MVVM。
将 datacontext 设置为 self 的示例都非常好,因为它们 "work" 但它们很简单。几乎没有人会在商业上这样做。

在 MVVM 中,您有一个视图模型 - class 实现了 inotifypropertychanged。这充当视图和模型之间的一种适配器。模型是您的数据,数据读取器的代码。
您的视图模型将调用该代码并将 observablecollection 中的数据呈现给视图。
这些 "rows" 数据中的每一个通常本身就是视图模型。

有多种方法可以实例化视图模型并将其设置为视图的数据上下文。 XAML.
中最简单的做法之一 你可以在这里看到一些非常基本的介绍代码:

https://social.technet.microsoft.com/wiki/contents/articles/31915.wpf-mvvm-step-by-step-1.aspxhttps://social.technet.microsoft.com/wiki/contents/articles/32164.wpf-mvvm-step-by-step-2.aspx

几乎所有商业团队都使用像 entity framework 或 dapper 这样的 ORM,其中 returns 对象填充了数据,而不必逐列工作。

不幸的是,从没有 mvvm 经验到工作商业级数据库导向应用程序的步骤是巨大的,因此在论坛中解释所有这些 post 并不是那么实际。