WPF 数据绑定到另一个类 [英] WPF databinding to an other class

查看:33
本文介绍了WPF 数据绑定到另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个 WPF UI.MainWindow.xaml.cs 中存在以下代码:

I've created a WPF UI. The following code exists in MainWindow.xaml.cs:

namespace AWPFProject
{
    public partial class MainWindow : Window
    {
        private readonly ServiceLogic serviceLogic;

        public MainWindow()
        {
            InitializeComponent();
            serviceLogic = new ServiceLogic ();
        }
    }
}

Servicelogic 是我的中心类.从那里调用方法或类来处理诸如数据库管理之类的事情.

Servicelogic is my central class. From there, methods or classes are called to handle stuff like database management.

现在,ServiceLogic 类具有我想要绑定到的值.例如,我有一个组合框,可以在其中显示我的用户.XAML 看起来像这样:

Now, that ServiceLogic class has the values I'd like to bind to. For example, I have a combobox where I can show my users. The XAML looks like this:

<ListBox Height="100" HorizontalAlignment="Left" Margin="6,44,0,0" 
 Name="listBox_detected" VerticalAlignment="Top" Width="120" 
 ItemsSource="{Binding Path=ServiceLogic.Users}" />

当我运行应用程序时,列表仍然是空的.我还需要做什么才能在我的列表中获取这些信息?

When I run the application, the list remains emtpy. What else do I need to do to get that information in my list?

推荐答案

您需要更改一些内容以使其在您的场景中起作用:

You need to change a few things to make this work in your scenario:

  1. 为您的窗口设置正确的 DataContext:

  1. Set the correct DataContext for your window:

public MainWindow()
{   
    InitializeComponent();
    DataContext = new ServiceLogic();
}

  • 确保 ServiceLogic 有一个名为 Users 的公共属性:

  • Make sure that ServiceLogic has a public property named Users:

    public List<User> Users { get; set; }
    

    如果您想在运行时向此列表添加/删除项目,请考虑使用 ObservableCollection,因为这会自动通知 UI 任何更改.

    if you want to add/remove items to this List at runtime, consider using an ObservableCollection<T> as this will notify the UI of any changes automatically.

    更新 xaml 的绑定逻辑,以便绑定到正确的列表.还要设置 DisplayMemberPath 属性或添加模板,以便很好地显示对象:

    Update the binding logic of your xaml, so that you bind to the correct list. Also set the DisplayMemberPath property or add a template so that the objects are displayed nicely:

    <ListBox ItemsSource="{Binding Path=Users}" DisplayMemberPath="Name"/>
    

    <ListBox ItemsSource="{Binding Path=Users}">
    <ListBox.ItemTemplate>
         <DataTemplate>
                <...your data template, like grid or stackpanel/>
         </DataTemplate>
    </ListBox.DataTemplate>
    

    使用 DisplayMemberPath 时,请确保用户类具有正确的属性.将以下内容添加到 User.cs:

    When using DisplayMemberPath, make sure the User-class has the correct properties. Add the following to User.cs:

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    } 
    

  • 这篇关于WPF 数据绑定到另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆