简体   繁体   English

将 Listbox 的 Itemsource 绑定到 Code behind 中的方法

[英]Binding the Itemsource of a Listbox to a method in Code behind

I have a Database and a XAML File an in there I have two Listboxes, the first one ( lbAg ) to list the topics ( ag_name , like finances, HR, etc.) and the second one ( liAn ) to list the tasks in that field which have to be done ( an_anligen , like paying the accountant etc..).我有一个数据库和一个 XAML 文件,在那里我有两个列表框,第一个( lbAg )列出主题( ag_name ,如财务、人力资源等),第二个( liAn )列出其中的任务必须完成的字段( an_anligen ,如支付会计师等)。 The thing is, I want the Items of liAn to be the tasks of the selected Item from liAg , but only if the attribute an_fertig (an_done) to be false.问题是,我希望 liAn 的项目成为liAg中所选项目的任务,但前提是属性 an_fertig (an_done) 为假。 This I want to achieve by binding it to a method in the code behind.我想通过将其绑定到后面代码中的方法来实现这一点。

Please help, Thanks in advance.请帮助,在此先感谢。 XAML: XAML:

<ListBox Grid.Column="0" 
         Grid.RowSpan="2"
         x:Name="liAg" 
         Loaded="liAg_Loaded" 
         DisplayMemberPath="ag_name"  />

<ListBox Grid.Column="1" 
         Grid.RowSpan="2"
         x:Name="liAn"  
          ItemsSource="{Binding liAn_Items}"
         DisplayMemberPath="an_titel" />

Code-behind:代码隐藏:

public partial class Main : UserControl
{
    public Main()
    {
        InitializeComponent();
    }

    DbEntities db = new DbEntities();

    private void liAg_Loaded(object sender, RoutedEventArgs e)
    {
        liAg.ItemsSource = db.ag_arbeitsgemeinschaft.ToList();
    }

    private void liAn_Items(object sender, RoutedEventArgs e)
    {
        string liag = liAg.SelectedItem.ToString();
        Console.WriteLine(liag);

        var erg = from a in db.an_anliegen
            where a.an_ag == liag && a.an_fertig != true
            select a;

        liAn.ItemsSource = erg.ToList();
    }
}

If you really want to bind to a method, you can use the ObjectDataProvider : Microsoft Docs: How to: Bind to a Method .如果您确实想绑定到方法,可以使用ObjectDataProviderMicrosoft Docs:如何:绑定到方法

You have many options.你有很多选择。 You can make use of the ListBox.SelectionChanged event to trigger the database query.您可以使用ListBox.SelectionChanged事件来触发数据库查询。

I highly recommend not to mix XAML data binding and direct property assignment using C#.我强烈建议不要混合使用 XAML 数据绑定和使用 C# 的直接属性分配。 You should use data binding when possible.您应该尽可能使用数据绑定。

I have created some DependencyProperty data source properties for the ListBox.ItemsSource properties to bind to.我为要绑定的ListBox.ItemsSource属性创建了一些DependencyProperty数据源属性。 Since you didn't supplied any details about your data item type, I bound the ListBox to a collection of the fictional DataItem type:由于您没有提供有关数据项类型的任何详细信息,因此我将ListBox绑定到虚构DataItem类型的集合:

MainWindow.xaml.cs主窗口.xaml.cs

partial class MainWindow : Window
{
  public static readonly DependencyProperty DataItemsProperty = DependencyProperty.Register(
    "DataItems",
    typeof(IEnumerable),
    typeof(MainWindow),
    new PropertyMetadata(default(IEnumerable)));

  public IEnumerable DataItems
  {
    get => (IEnumerable) GetValue(MainWindow.DataItemsProperty);
    set => SetValue(MainWindow.DataItemsProperty, value);
  }

  public static readonly DependencyProperty TasksProperty = DependencyProperty.Register(
    "Tasks",
    typeof(IEnumerable),
    typeof(MainWindow),
    new PropertyMetadata(default(IEnumerable)));

  public IEnumerable Tasks
  {
    get => (IEnumerable) GetValue(MainWindow.TasksProperty);
    set => SetValue(MainWindow.TasksProperty, value);
  }

  public MainWindow()
  {
    this.DataItems = db.ag_arbeitsgemeinschaft.ToList();
  }

  private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    // Cast the ListBox.SelectedItem from object to the data type
    DataItem selectedItem = e.AddedItems.OfType<DataItem>().FirstOrDefault();
    if (selectedItem == null)
    {
      return;
    }

    // Access the selected item's members
    string displayedValue = selectedItem.ag_name;

    // Execute query
    var erg = from a in db.an_anliegen
            where a.an_ag == displayedValue && !a.an_fertig
            select a;

    // Update binding source of the ListBox named 'liAn'
    this.Tasks = erg.ToList();
  }
}

MainWindow.xaml主窗口.xaml

<Window>
  <ListBox x:Name="liAg" 
           ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, 
                         Path=DataItems}"
           DisplayMemberPath="ag_name"
           SelectionChanged="OnSelectionChanged" />

  <ListBox x:Name="liAn"  
           ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, 
                         Path=Tasks}"
           DisplayMemberPath="an_titel" />
</Window>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM