我是MVVM/WPF的新手,经过几个小时的研究,没有找到任何真正有用的工作答案,我决定给它一个去,尝试在这里问。WPF使用SelectedIndex从ViewModel中选择列表框中的项目
我想从列表框中选择一个项目,它使用List作为ItemSource。
相关视图模型:
public class FavoriteStructureVm : INotifyPropertyChanged
{
#region
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
public ObservableCollection<FavoriteDataVm> Favorites { get; set; }
public int SelectedIndex { get; set; }
private FavoriteDataVm _selectedItem;
public FavoriteDataVm SelectedItem
{
set
{
_selectedItem = value;
var item = (FavoriteDataVm)_selectedItem;
if (item.Type == FavoriteDataType.Add)
{
SelectedIndex = 1;
}
}
}
}
列表框默认包含的几个项目,最后一个总是被类型Add
,而如果选择,可以添加一个新的项目,在默认情况下选中或选择之一如果没有添加新项目,则先前选择的项目。 For Simplicity无论是否添加新项目,所选项目都将为1。
无论身在何处,什么我试图与OnPropertyChanged
更新它并没有在视图中更新的SelectedIndex,但通过添加/插入新FavoriteDataVm
为ObservableCollection<FavoriteDataVm> Favorites
,在视图中SelectedIndex
得到更新。 向列表中添加新项目的过程并不总是会发生,但我总想更新SelectedIndex
。
相关XAML:
<ListBox Name="favMenu" ItemsSource="{Binding Favorites}" SelectionMode="Single"
HorizontalAlignment="Center" VerticalAlignment="Top"
BorderThickness="0" Background="Transparent" Height="{Binding ElementName=window, Path=ActualHeight}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}"
>
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Background="Transparent" SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<!--changing default orientation-->
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border x:Name="Border"
BorderThickness="0" BorderBrush="Black" Background="{x:Null}"
Width="60" Height="60" CornerRadius="30" Margin="{Binding Margin}"
ToolTip="{Binding Name}">
<Image Source="{Binding ImageUri}" Width="60" Height="60" Stretch="UniformToFill">
<Image.Clip>
<EllipseGeometry RadiusX="30" RadiusY="30" Center="30,30"/>
</Image.Clip>
</Image>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我找到了一个解决办法,只是创建一个虚拟项目,并删除它,因为添加一些似乎更新视图的SelectedIndex
。我不认为它是一个解决方案,因为它有很多缺点。
所以这有点儿实际上提出了两个问题:
- 我如何获得更新列表框的
SelectedIndex
?
和新手的话,问题,因为我是新来的MVVM:
- 这是一个正确实施的MVVM?
感谢百忙之中阅读我的问题的时候了!我没有尝试把事件放在那里,所以它可能证明是可行的(最可能)。稍后当我回家并根据需要更新此线程时,我会试一试 – Rikidere