[英]How to prevent all buttons text in a listview from changing xamarin forms
I am wondering if someone could please help me or point me in the right direction. 我想知道是否有人可以帮助我或为我指明正确的方向。 I have a Listview that binds to a Viewmodel , This listview has a label and a button .
我有一个绑定到Viewmodel的Listview,这个listview有一个标签和一个按钮。 The listview is populated with music.
音乐播放列表视图。 When i press on the play button all the buttons that are populated with name of song in the listview has their name changed to stop , How do i prevent that from happening.
当我按下播放按钮时,在列表视图中填充有歌曲名称的所有按钮的名称都更改为stop,如何防止这种情况发生。 Please find code below.
请在下面找到代码。
public class MusicViewModel : INotifyPropertyChanged
{
public MusicViewModel()
{
GetMusic();
CommandText = "Play";
}
public List<AudioModel> _audioList;
public List<AudioModel> AudioList
{
get { return _audioList; }
set
{
_audioList = value;
OnPropertyChanged();
}
}
async void GetMusic()
{
var audioService = new AudioServices();
AudioList = await audioService.GetAudioAsync();
}
private string _commandText;
public string CommandText
{
get { return _commandText; }
set
{
_commandText = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CommandText"));
}
}
public ICommand _playCommand;
public ICommand PlayCommand
{
get
{
return _playCommand ?? (_playCommand = new Command((obj) =>
{
var item = (obj as AudioModel);
var id = item.souID;
if (CommandText == "Play")
{
CrossMediaManager.Current.Play("http://Example.co.za/Example.asp?fldPRK=souID&PRKvalue=" + id + "&fldBLOB=sousound&TableName=Sounds_Sound_Details&ACT=BLOB&width=250&square=yes", MediaFileType.Audio);
CommandText = "Stop";
}
else if (CommandText == "Stop")
{
CrossMediaManager.Current.Stop();
CommandText = "Play";
}
}));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
<ListView ItemsSource="{Binding AudioList}" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid x:Name="Item">
<StackLayout>
<Label Text="{Binding souName}" />
<Button Text="{Binding Source={x:Reference Name=RINGTONE},Path=BindingContext.CommandText}"
Command="{Binding Source={x:Reference Name=RINGTONE},Path=BindingContext.PlayCommand}"
CommandParameter="{Binding Source={Reference Item},Path=BindingContext}"/>
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
You are binding each item to the same, shared command in the MusicViewModel
. 您将每个项目绑定到
MusicViewModel
的相同共享命令。 That is why all items are updated when you change it. 这就是为什么更改所有项目时都会对其进行更新的原因。
What you probably want is to add the command to the AudioModel
. 您可能想要的是将命令添加到
AudioModel
。 That way it will only update for that specific entry. 这样,它将仅针对该特定条目进行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.