将Listbox的Itemsource绑定到代码隐藏中的方法



我有一个数据库和一个XAML文件,其中有两个列表框,第一个(lbAg(列出主题(ag_name,如财务、人力资源等(,第二个(liAn。问题是,我希望liAn的项目是liAg中所选项目的任务,但前提是属性an_fertig(an_done(为false。我想通过将它绑定到代码后面的方法来实现这一点。

请帮忙,提前谢谢。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" />

代码背后:

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();
}
}

如果您真的想绑定到方法,可以使用ObjectDataProvider:Microsoft文档:如何:绑定到方法。

你有很多选择。您可以使用ListBox.SelectionChanged事件来触发数据库查询。

我强烈建议不要使用C#混合XAML数据绑定和直接属性赋值。您应该尽可能使用数据绑定。

我为要绑定的ListBox.ItemsSource属性创建了一些DependencyProperty数据源属性。由于您没有提供任何有关数据项类型的详细信息,我将ListBox绑定到虚构的DataItem类型的集合:

主窗口.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();
}
}

主窗口.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>

最新更新