I'm relatively new to WPF, and MVVM is over my head right now, so I'm looking for a solution to bind Combo Box ItemsSource of a user control to a parent window's member. I've looked up many examples and related answers on stackoverflow and elsewhere, but they refer to MVVM design, and I'm trying to get the basics of WPF right now.
Following is what I've tried to do based on the second suggestion from Add items to ComboBox at runtime? and advice from How do I use WPF bindings with RelativeSource?. You'll notice UserControl1.xaml uses RelativeSource to bind the combo box's ItemsSource.
MainWindow.xaml
<Window x:Class="DataBindingTest1.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:DataBindingTest1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:UserControl1/>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Collections.Generic;
using System.Windows;
namespace DataBindingTest1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public List<string> memberData;
public MainWindow()
{
memberData = new List<string>();
memberData.Add("Item 1");
memberData.Add("Item 2");
memberData.Add("Item 3");
InitializeComponent();
}
}
}
UserControl1.xaml
<UserControl x:Class="DataBindingTest1.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:DataBindingTest1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=memberData}"/>
</Grid>
</UserControl>
UserControl1.xaml.cs
using System.Windows.Controls;
namespace DataBindingTest1
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
}
}