我是MVVM / WPF的新手,经过几个小时的研究,没有为我的项目找到任何真正有用/可行的答案,我决定试一试,试试这里问 .
我想从我的Listbox中选择一个Item,它使用List作为ItemSource .
相关的ViewModel:
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;
}
}
}
}
ListBox默认包含一些项目,最后一个项目始终是 Add
类型之一,如果选择该项目,则可以添加新项目并默认选择它,或者如果没有添加新项目,则选择先前选择的项目 . For Simplicity 所选项目只是1,无论是否添加新项目 .
无论我在哪里尝试更新 OnPropertyChanged
它都没有更新视图中的SelectedIndex,但是,通过在 ObservableCollection<FavoriteDataVm> Favorites
中添加/插入新的 FavoriteDataVm
,视图中的 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
. 我不认为这是一个解决方案,因为它带来了许多缺点 .
所以这实际上提出了两个问题:
- 如何更新ListBox的
SelectedIndex
?
还有一个初学者问题,因为我是MVVM的新手:
- 这是MVVM的正确实现吗?
2 回答
您可以通过获取源集合中
SelectedItem
的索引来获取所选索引:您可以通过设置
SelectedItem
属性来选择项目:您不应该同时绑定
ListBox
的SelectedItem
和SelectedIndex
属性 . 这些必须同步 . 从XAML中删除SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}"
.另请注意,如果要动态更新源属性,则需要为此属性引发
PropertyChanged
以使视图刷新:您没有更新SelectedIndex声明应如下所示
这样,当selectedindex更改时,将通知列表
"Sorry if there are any typos, i wrote this directly here and not in a code editor so you might get typos"