我创建了一个列表视图,其中的项目按不同的类别排序。我试图让listview的selectedItem进入我的Viewmodel中的属性,我遵循常规方法只是设置一个绑定到SelectedItem属性。
但是,因为我现在实际上只是将datacontext设置为我的可观察集合,而不是触及ItemsSource属性(或者我是吗?),我相信我缺少一些奇特的xaml代码来使SelectedItem的绑定工作。希望有人遇到过类似的问题。 xaml代码和viewmodel中声明的2个属性在下面显示。
<UserControl.Resources>
<CollectionViewSource x:Key="TileChangeType"
Source="{Binding TileChangeList.TileChangeListEntries}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Type" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</UserControl.Resources>
<ListView Grid.Column="0" x:Name="gridTiles" VirtualizingPanel.IsVirtualizing="False" VirtualizingPanel.IsVirtualizingWhenGrouping="False"
DataContext="{StaticResource TileChangeType}"
SelectedItem="{Binding SelectedTileChange}"
ItemsSource="{Binding IsAsync=True}">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True">
<Expander.Header>
<TextBlock Background="Aqua" Text="{Binding Path=Name}"/>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<DataGridRowsPresenter/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</ListView.GroupStyle>
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="X" DisplayMemberBinding="{Binding X}" />
<GridViewColumn Header="Y" DisplayMemberBinding="{Binding Y}" />
<GridViewColumn Header="Z" DisplayMemberBinding="{Binding Z}" />
<GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}" Width="40"/>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
模型&#34; SelectedTileChange&#34;声明如下:
public TileChange SelectedTileChange
{
get;
set;
}
//Class contains an Observable Collection of the TileChange class (same class as SelectedItem is binding to)
//E.g. ObservableCollection<TileChange> tileChangeListEntries;
public TileChangeList TileChangeList
{
get;
set;
}
答案 0 :(得分:1)
假设usercontrol的datacontext设置为包含SelectedTileChange
属性的viewmodel,您可以绑定到SelectedItem
属性,如下所示:
SelectedItem="{Binding DataContext.SelectedTileChange,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
这将找到usercontrol,并绑定到其datacontext上的SelectedTileChange
属性。
但通常您只需将ListView
直接绑定到CollectionViewSource
,而不是设置其datacontext。这样您就不需要创建这种RelativeSource
绑定:
<ListView ItemsSource="{Binding Source={StaticResource TileChangeType}}"
SelectedItem="{Binding SelectedTileChange}" />