簡體   English   中英

WPF數據綁定到其他類

[英]WPF databinding to an other class

我已經創建了一個WPF UI。 MainWindow.xaml.cs存在以下代碼:

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

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

Servicelogic是我的中心階層。 從那里,調用方法或類來處理數據庫管理之類的東西。

現在,該ServiceLogic類具有我想要綁定的值。 例如,我有一個組合框,我可以向我的用戶展示。 XAML看起來像這樣:

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

當我運行應用程序時,列表仍然是emtpy。 我還需要做些什么才能在我的列表中獲取這些信息?

您需要更改一些內容才能使其在您的方案中正常工作:

  1. 為您的窗口設置正確的DataContext:

     public MainWindow() { InitializeComponent(); DataContext = new ServiceLogic(); } 
  2. 確保ServiceLogic具有名為Users的公共屬性

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

    如果要在運行時向此List添加/刪除項,請考慮使用ObservableCollection<T>因為這將自動通知UI任何更改。

  3. 更新xaml的綁定邏輯,以便綁定到正確的列表。 還要設置DisplayMemberPath屬性或添加模板,以便很好地顯示對象:

     <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> 

  4. 使用DisplayMemberPath ,請確保User-class具有正確的屬性。 將以下內容添加到User.cs:

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

這里ItemsSource="{Binding Path=ServiceLogic.Users}"您聲明數據具有公共屬性 ServiceLogic

其次,您通過DataContext獲取數據

更改構造函數:

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

並更改綁定到這一個:

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

在Binding中,我刪除了ServiceLogic,因為SL代表數據項。 和路徑 - 是財產的路徑。

我認為你需要設置ListBox的“DisplayMemberPath”屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM