我有一个Expander
在我的视图,每次我触摸它打开并显示数据。是否可以打开Expander
或关闭它从ViewModel?我想做的是,Expander
可以打开或关闭它按下一个Button
。
MainPage.xaml:
<StackLayout>
<StackLayout>
<CollectionView>
<CollectionView.ItemTemplate>
<DataTemplate>
<ContentView>
<Frame>
<StackLayout>
<Expander x:Name="expander"></Expander>
</StackLayout>
</Frame>
</ContentView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
<StackLayout>
<ImageButton Source="img1" Command="{Binding xxxCommand}" CommandParameter="{Binding Source={x:Reference expander}, Path=.}"/>
</StackLayout>
</StackLayout>
ViewModel:
xxxCommand = new Command((sender)=> {
var exp = sender as Expander;
exp.IsExpanded = !exp.IsExpanded;
//...
});
当我打开应用程序时,我得到这个异常:
Xamarin.Forms.Xaml。找不到对象由扩展器引用
您可以将Expander作为参数传递给按钮的Command。
设置Expander的名称
<Expander x:Name="exp">
<Button Text="XXX" Command="{Binding xxxCommand}" CommandParameter="{Binding Source={x:Reference exp}, Path=.}" />
在ViewModel
xxxCommand = new Command((sender)=> {
var exp = sender as Expander;
exp.IsExpanded = !exp.IsExpanded;
//...
});
更新在你的情况下,你可以使用数据绑定
<StackLayout>
<Expander IsExpanded="{Binding IsExpanded}"></Expander>
</StackLayout>
<ImageButton Source="img1" Command="{Binding xxxCommand}"/>
在你的模型中添加一个新属性
public class YourModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyname)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
}
public bool isExpanded;
public bool IsExpanded
{
get { return isExpanded; }
set
{
isExpanded= value;
OnPropertyChanged("IsExpanded");
}
}
//...other properties
}
在ViewModel//list here is the ItemsSource of your listview
ObservableCollection<YourModel> list = new ObservableCollection<YourModel>();
//list.Add();
//list.Add();
//list.Add();
//list.Add();
Command xxxCommand = new Command(()=> {
//if you want to open the first Expander
list[0].IsExpanded = true;
});