我想在UserContorl中创建一个ListBox,而不是使用该userControl在许多页面中显示和“管理”该列表。
例如,我有一个卡车列表,每个对象卡车都有一些属性,如名称,id ...
现在我创建自己的UserControl
<UserControl
x:Class="Crud.View.ListboxInUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Crud.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Name="myUserControl"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<ListBox x:Name="aName" ItemsSource="{Binding ??}">
<StackPanel>
<StackPanel Orientation="Vertical" Margin="0,20,0,0">
<TextBlock Text="Id"/>
<TextBlock Text="{Binding Id}" />
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,20,0,0">
<TextBlock Text="Name"/>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</StackPanel>
</ListBox>
</Grid>
如何绑定代码中的项目?
如何管理列表中的“点击”?
在Page.xaml中我想写类似
的内容<LUC:ListboxInUserControl x:Name="MyListbox DataContext="{Binding}"/>
并在
背后的代码中private ObservableCollection<Truck> TestList { get; set; }
...
TestList = await TruckService.GetAll(); //a method to get the list
MyListbox.MyItemsSource = TestList;
答案 0 :(得分:1)
将列表框添加到UserControl,
<ListBox x:Name="aName" SelectionChanged="aName_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel Orientation="Vertical" Margin="0,20,0,0">
<TextBlock Text="Id"/>
<TextBlock Text="{Binding Id}" />
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,20,0,0">
<TextBlock Text="Name"/>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
添加用于获取选择的事件处理程序和listbox的公共属性,以便在后面的用户控制代码中绑定对象,
public event EventHandler<EventArgs> SelectionChangedEvent;
public ListBoxInUserControl()
{
this.InitializeComponent();
}
private void aName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectionChangedEvent(sender, new EventArgs());
}
private ListBox myVar;
public ListBox MyProperty
{
get { return aName; }
set { aName = value; }
}
然后您可以在xaml中添加此usercontrol,
<local:ListBoxInUserControl x:Name="uc_ListBoxInUserControl" SelectionChangedEvent="uc_ListBoxInUserControl_SelectionChangedEvent"> </local:ListBoxInUserControl>
在后面的代码中,您可以绑定数据,
uc_ListBoxInUserControl.MyProperty.ItemsSource = TestList;
和访问选择已更改事件,
private void uc_ListBoxInUserControl_SelectionChangedEvent(object sender, EventArgs e)
{
}