gpt4 book ai didi

wpf - 如何使用 MVVM 在 ListView 中设置特定项目?

转载 作者:行者123 更新时间:2023-12-03 10:27:06 24 4
gpt4 key购买 nike

我有一个这样的 Button 元素的 ListView:

 <ListView ItemsSource="{Binding DummyModelList}" SelectedItem="{Binding SelectedItem}">
<ListViewItem >
<Button Name="test" Grid.Row="0" Grid.Column="10" Grid.ColumnSpan="4" Grid.RowSpan="4" VerticalAlignment="Center" Background="Transparent" Command="{Binding DataContext.TestCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}}">
<Button.Template>
<ControlTemplate>
<Grid RenderTransformOrigin="0.5,0.5" x:Name="bg">
<Image Source="{Binding DataContext.SlidOnOffImg , RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}}"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</ListViewItem >

在我的 View 模型中:
public class MyViewModel:BindableBase
{

private ObservableCollection<Slide> dummyModelList;
public ObservableCollection<Slide> DummyModelList
{
get { return dummyModelList; }
set
{
dummyModelList = value;
OnPropertyChanged(() => DummyModelList);
}
}

public string SlidOnOffImg { get; set; }


private int selectedItem;
public int SelectedItem //this property stores currently selected item from thumbnails list
{
get { return selectedItem; }

set
{
selectedItem = value;
OnPropertyChanged(() => SelectedItem);
}

public CompositeCommand TestCommand { get; set; }

public MyViewModel(IRegionManager regionManager, IEventAggregator eventAggregator) //constructor
{

dummyModelList = new ObservableCollection<ISlide>() { new Slide(), new Slide(), new Slide()};

TestCommand = new CompositeCommand();
TestCommand.RegisterCommand(new DelegateCommand(ChangeImage));
}

private void ChangeImage()
{

if (dummyModelList.ElementAt(selectedItem).SlideExcluded)
dummyModelList.ElementAt(selectedItem).SlideExcluded = false;
else
dummyModelList.ElementAt(selectedItem).SlideExcluded = true;

SlidOnOffImg = dummyModelList.ElementAt(selectedItem).SlideONOFFImgPath;
OnPropertyChanged(() => SlidOnOffImg);
}
}

在我的模型中:
public class Slide : ISlide
{
public bool SlideExcluded { get; set; }

public string SlideONOFFImgPath
{
get
{
if(SlideExcluded)
return "/Assets/Visible_OFF.png";
else
return "/Assets/Visible_ON.png";
}

}

}

我的目标是让按钮的图像在按钮单击时在两个图像路径之间切换。它可以工作,但问题是列表中的所有按钮都会在单击某些按钮时更改图像路径。我只想要单击以更改图像路径的那个。

如何解决这个问题?

最佳答案

您需要在 XAML 中绑定(bind)到 SelectedIndex 而不是 SelectedItem。 SelectedIndex 保存对列表中项目索引的引用,SelectedItem 保存对列表中对象的引用。要么,要么更改您的 View 模型以使用实际对象而不是索引。

关于wpf - 如何使用 MVVM 在 ListView 中设置特定项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36746018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com