我曾经遇到类似的问题,我使用以下代码解决了它。我在这里发布,希望能对其他人有所帮助。
如果我的回答对你有帮助,请不要忘记点赞。
EmpUserControl.xaml文件
<UserControl x:Class="Sample.UserControls.EmpUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:uc="clr-namespace:Sample.UserControls"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0">First Name: </Label>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding FirstName}" />
<Label Grid.Row="1" Grid.Column="0">Last Name: </Label>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding LastName}" />
</Grid>
</UserControl>
EmpUserControl.xaml.cs
namespace Sample.UserControls
{
public partial class EmpUserControl : UserControl
{
public EmpUserControl()
{
InitializeComponent();
}
}
}
MainWindow.xaml 文件
<Window x:Class="Sample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Sample"
xmlns:uc="clr-namespace:Sample.UserControls"
mc:Ignorable="d"
Title="MainWindow" Height="600" Width="900" WindowStyle="SingleBorderWindow"
ResizeMode="NoResize">
<Grid>
<ListBox Name="LbEmp" Width="220" Height="220" >
<ListBox.ItemTemplate>
<DataTemplate>
<uc:EmpUserControl DataContext="{Binding}"></uc:EmpUserControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
MainWindow.xaml.cs 文件
namespace Sample
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void LoadEmpListBox(){
var empList = new List<EmpViewModel>{
new EmpViewModel { FirstName = "Rajeev", LastName = "Kumar" },
new EmpViewModel { FirstName = "Sita", LastName = "Hedge" },
new EmpViewModel { FirstName = "Deepika", LastName = "PL" }
};
LbEmp.ItemsSource = empList;
}
}
}
EmpViewModel 模型
public class EmpViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}