是否可以从 ViewModel 打开 Expander?

Is it possible to open Expander from ViewModel?

我的视图中有一个 Expander,每次我触摸它时它都会打开并显示数据。是否可以从 ViewModel 打开或关闭 Expander?我想要做的是 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>

视图模型:

    xxxCommand = new Command((sender)=> {

     var exp = sender as Expander;
     exp.IsExpanded = !exp.IsExpanded;
     //...
            
});

当我打开应用程序时,出现以下异常:

Xamarin.Forms.Xaml.XamlParseException: Can not find the object referenced by expander.

您可以将扩展器作为参数传递给按钮的命令。

设置Expander的名称

 <Expander x:Name="exp">
 <Button Text="XXX"  Command="{Binding xxxCommand}" CommandParameter="{Binding Source={x:Reference exp}, Path=.}" />

在视图模型中

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

}

在视图模型中

//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;


});