我正在尝试制作一个WPF程序,我有一个AgreementModel
。然后使用ListView
控件显示协议,但仅显示几个关键属性。然后,我有一个StackPanel
控件,用于显示所选项目的所有协议详细信息。我为每种显示项目的方式制作了DataTemplate
。
这就是我的问题所在。虽然我可以轻松地将ListView绑定到协议(我的视图模型中的ObservableCollection
),但我根本无法弄清楚如何将细节绑定到选定的协议(视图模型中的AgreementModel
)。
我能找到的一切似乎与绑定集合有关。如何仅将所选项目绑定到StackPanel
或类似项?
查看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#
私人AgreementModel选择协议;
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;
}
答案 0 :(得分:3)
IEnumerable
用于显示集合,或者更确切地说是AgreementModel
项目。
如果您只想在StackPanel
中显示当前所选DataContext
的详细信息,则可以将其SelectedAgreement
绑定到ContentControl
属性或使用{{ 1}}:
<ContentControl Content="{Binding SelectedAgreement}" ContentTemplate="{StaticResource agreementDetailTemplate}" />
<StackPanel DataContext="{Binding SelectedAgreement}">
...
</StackPanel>
您还应确保视图模型类实现INotifyPropertyChanged接口,并在设置PropertyChanged
属性时引发SelectedAgreement
事件。
否则,当您选择ContentControl
中的项目时,StackPanel
/ ListBox
将不会更新。
答案 1 :(得分:1)
您需要将SelectedIndex
绑定到ViewModel中的属性(例如SelectedAgreementIndex
)。然后,在SelectedAgreementIndex
属性的setter中,您可以根据SelectedAgreement
设置SelectedIndex
属性。然后它只是使用例如SelectedAgreement
绑定到ContentControl
。在使用您的数据模板的视图中{{1}}。