我正在尝试使用mvvm选择 ListView 中的所有项。使用代码隐藏,我尝试了 SelectAll()和 foreach 来选择它们,但我想像我的项目的其余部分一样使用MVVM。有什么想法吗?
这是listview:
<ListView x:Name="TransformerList" ItemsSource="{Binding CurrentStations}" Margin="16,250,0,10.4" SelectionMode="Multiple" HorizontalAlignment="Left" Width="411">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Select">
<i:InvokeCommandAction Command="{Binding SeeAllCustomersCommand}" CommandParameter="{Binding Item1}"/>
</i:EventTrigger>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectedCustomersChangedCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}" />
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=TransformerIsSelected}" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Nettstasjon" Width="70" DisplayMemberBinding="{Binding Path=Name}" />
<GridViewColumn Header="Område" Width="210" DisplayMemberBinding="{Binding Path=Area}"/>
<GridViewColumn Header="Radial" Width="110" DisplayMemberBinding="{Binding Path=Radial}"/>
</GridView>
</ListView.View>
</ListView>
和按钮:
public ICommand cmd_VelgAlle { get { return new RelayCommand(on_cmd_VelgAlle); } }
private void on_cmd_VelgAlle()
{
foreach (item i in CurrentStations) //the item here gives an error "type or namespace could not be found"
{
i.TransformerIsSelected = true;
}
}
和mvvm:
private bool _TransformerIsSelected;
public bool TransformerIsSelected
{
get { return _TransformerIsSelected; }
set
{
_TransformerIsSelected = value;
RaisePropertyChanged("TransformerIsSelected");
}
}
答案 0 :(得分:2)
您需要创建ListViewItem
Style
:
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListView.ItemContainerStyle>
在Model
class:
public bool IsSelected
{
get { return isSelected; }
set
{
isSelected = value;
RaiseChange("IsSelected");
}
}
并迭代您的ItemSource,为所有项目设置IsSelected
true
。( 在ViewModel中 )
foreach(item i in yourCollection)
{
i.IsSelected = true;
}
<强>更新强>
将样式用作:
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=TransformerIsSelected}" />
</Style>
</ListView.ItemContainerStyle>
命令:
private void on_cmd_VelgAlle()
{
//Item is the class your CurrentStations is made of(i guess something like `station` in your design)
//i.e if CurrentStations is list of string then Item will be string
foreach (Item i in CurrentStations)
{
i.TransformerIsSelected = true;
}
}