Here is the simplest example that I can create....
1. Create new WPF project
2. Add
UserControl1
UserControl
3. USe the following code:
XAML
<UserControl x:Class="WpfUserControlBinding.UserControl1"
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:local="clr-namespace:WpfUserControlBinding"
mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800">
<ListBox ItemsSource="{Binding FileNames}" />
</UserControl>
Code-Behind
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
DataContext = this;
}
public ObservableCollection<string> FileNames { get; set; } = new();
}
4. Update the MainWindow with the following:
XAML
<Window x:Class="WpfUserControlBinding.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:WpfUserControlBinding"
mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
<local:UserControl1 x:Name="MyUserControl"/>
</Window>
Code-Behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
foreach (string entry in Directory
.EnumerateFileSystemEntries(Environment.CurrentDirectory))
MyUserControl.FileNames.Add(Path.GetFileName(entry));
}
}
Run the app and the
ListBox
will be populated with filenames.