I am trying to make a WPF program, where I have an AgreementModel
. The agreements are then shown using a ListView
control, but displaying only a few key properties. I then have a StackPanel
control, which I use to display all agreement details, for the selected item. I have made a DataTemplate
for each of the ways of displaying the item.
And this is where my issue is. While I can easily bind the ListView to the agreements (an ObservableCollection
in my view model), I simply cannot figure out how to bind the details to the selected agreement (an AgreementModel
in the view model).
Everything I can find seems to relate to binding collections. How do I bind only the selected item to a StackPanel
or similar?
View XAML
<UserControl.Resources>
<!--Template for list view-->
<DataTemplate x:Key="agreementRowTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock
Text="{Binding Path=Property1}" />
<TextBlock
Text="{Binding Path=Property2}" />
<TextBlock
Text="{Binding Path=Property3}" />
</StackPanel>
</DataTemplate>
<!--Template for the detail view-->
<DataTemplate x:Key="agreementDetailTemplate">
<StackPanel>
<TextBlock
Text="Property 1:" />
<TextBox
Text="{Binding Path=Property1}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="600" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<!-- This list view works as intended -->
<ListBox
Grid.Column="1"
ItemsSource="{Binding Agreements}"
SelectedItem="{Binding SelectedAgreement}"
ItemTemplate="{StaticResource agreementRowTemplate}"/>
<!-- I am trying to add my detail view here -->
<ItemsControl ItemTemplate="{StaticResource agreementDetailTemplate}" ItemsSource="{Binding SelectedAgreement}">
</ItemsControl>
</Grid>
ViewModel C#
private AgreementModel selectedAgreement;
public ValuationViewModel()
{
LoadAgreements();
}
public ObservableCollection<AgreementModel> Agreements
{
get; set;
}
// I have tried 'return Agreements[0]' to check if this was the problem
public AgreementModel SelectedAgreement
{
get { return _selectedAgreement; }
set { selectedAgreement = value; }
}
public void LoadAgreements()
{
ObservableCollection<AgreementModel> agreements =
new ObservableCollection<AgreementModel>();
agreements.Add(new AgreementModel { Property1 = 123, Property2 = "Some Text", Property3 = "Status: OK" });
agreements.Add(new AgreementModel { Property1 = 456, Property2 = "Some Text", Property3 = "Status: Not OK" });
agreements.Add(new AgreementModel { Property1 = 789, Property2 = "Some Text", Property3 = "Status: Somewhat OK" });
Agreements = agreements;
}