我是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