In my application I'd like to have a drop-down box to choose a table to edit (of about 20). Each table should be represented by its own WPF DataGrid. (I'd thought about using a single DataGrid and creating a set of new columns at runtime with code-behind, but that doesn't seem very XAML-ish.)
My drop-down is in a UserControl (since it's part of a larger application). I believe (from my research) that the placeholder for the one-of-20 DataGrids should be a ContentControl used as a placeholder here:
<UserControl x:Class="MyClass" ...
xmlns:my="clr-namespace:MyNamespace"
DataContext="{Binding ViewModel}">
<StackPanel>
<Grid>
<ComboBox Name="DataPaneComboBox" HorizontalAlignment="Stretch"
IsReadOnly="True" MinWidth="120"
Focusable="False" SelectedIndex="0"
DockPanel.Dock="Left" Grid.Column="0"
SelectionChanged="DataPaneComboBox_SelectionChanged">
<ComboBoxItem Name="FirstOption" Content="Choice 1" />
<ComboBoxItem Name="SecondOption" Content="Choice 2" />
<ComboBoxItem Name="ThirdOption" Content="Choice 3" />
</ComboBox>
</Grid>
<ContentControl Name="DataGridView" Margin="0,3,0,3" Content="{Binding CurrentView}" />
</StackPanel>
Here's my code-behind for this class:
public partial class MyClass : UserControl {
private MyViewModel ViewModel {
get; set;
}
public MyClass() {
InitializeComponent();
ViewModel = new MyViewModel();
ViewModel.CurrentView = new DataGridChoice1();
}
}
And the ViewModel (class ObservableObject implements the INotifyPropertyChanged interface):
public class MyViewModel : ObservableObject {
private UserControl _currentView;
public UserControl CurrentView {
get {
if (this._currentView == null) {
this._currentView = new DatGridChoice1();
}
return this._currentView;
}
set {
this._currentView = value;
RaisePropertyChanged("CurrentView");
}
}
#endregion
}
And one of the 20 or so UserControls that can be substituted in at runtime:
<UserControl x:Class="Choice1Control"
xmlns:my="clr-namespace:MyNamespace">
<DataGrid ItemsSource="{Binding Choice1Objects}" />
<!-- ... -->
</DataGrid>
</UserControl>
When the user changes the drop-down I'd like the program to load the appropriate DataGrid. Right now I can't see the child UserControl (here, Choice1Control
). I've added the child directly (without the intervening ContentControl) and it works fine.
I've tried just about every combination of DataContext and UserControl content binding. I'm new to WPF, so I'm probably missing something glaringly obvious. Thanks!