基于用户控件的Xamarin重用视图模型
在我的MainPage.xaml(一个ContentPage)中,我有两个用户控件。 两者都是ContentView,加载方式如下:基于用户控件的Xamarin重用视图模型,xamarin,xamarin.forms,Xamarin,Xamarin.forms,在我的MainPage.xaml(一个ContentPage)中,我有两个用户控件。 两者都是ContentView,加载方式如下: <local:MyView2 HorizontalOptions="Start" VerticalOptions="Fill"> <local:MyView2.BindingContext> <viewmodels:NavbarViewMo
<local:MyView2 HorizontalOptions="Start"
VerticalOptions="Fill">
<local:MyView2.BindingContext>
<viewmodels:NavbarViewModel />
</local:MyView2.BindingContext>
<local:MyView2.Triggers>
<DataTrigger TargetType="{x:Type local:MyView2}" Binding="{Binding IsPresented}" Value="True">
<DataTrigger.EnterActions>
<local:MenuTrigger IsPresented="True"/>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<local:MenuTrigger IsPresented="False" />
</DataTrigger.ExitActions>
</DataTrigger>
</local:MyView2.Triggers>
</local:MyView2>
// omitted myview1, they are basically the same
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Universal_ONE.MyView1">
<Frame BackgroundColor="#385C6C"
Padding="0,0,0,0">
<ImageButton Source="outline_menu_white_24.png"
Command="{Binding PresentMenu}"
WidthRequest="24"
HeightRequest="24"
Margin="15,0,0,0"
BackgroundColor="Transparent"
HorizontalOptions="StartAndExpand" />
</Frame>
</ContentView>
编辑2:
我补充说:
x:DataType="viewmodels:NavbarViewModel
对于这两个ContentView,这将删除没有DataContext的错误。但是,绑定仍然不起作用
工作解决方案:
现在,我在app.xaml中将viewmodel添加为staticresource,并在任何地方重用它,包括在用户控件中。我希望在将来的某个时候再看看这个问题。请发布
NavbarViewModel
@Jason我已经添加了viewmodel代码和我得到的错误您在代码中做了什么来修改BindingContext吗?没有,它只有initializeComponent()。我没有接触任何文件中的任何代码。如果您愿意,我可以将整个文件上传到Github repo
public class NavbarViewModel : INotifyPropertyChanged
{
public NavbarViewModel()
{
isPresented = false;
PresentMenu = new Command(() => IsPresented = !IsPresented);
}
bool isPresented;
public bool IsPresented
{
get => isPresented;
set
{
isPresented = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsPresented)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ICommand PresentMenu { private set; get; }
}
x:DataType="viewmodels:NavbarViewModel