-2

我的视图中有一个Expander,每次触摸它都会打开并显示数据。Expander是否可以从 ViewModel打开或关闭它?我想要做的是Expander可以通过按 a 打开或关闭它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:找不到扩展器引用的对象。

4

1 回答 1

0

您可以将 Expander 作为参数传递给 button 的 Command 。

设置扩展器的名称

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


});
于 2021-01-28T10:49:57.620 回答