如何解决Xamarin 在用户控件上重用视图模型
在作为 ContentPage 的 MainPage.xaml 中,我有两个用户控件。 两者都是 ContentView 并且像这样加载:
<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
My MainPage 与 MyView1 和 2 具有不同的视图模型,后者是内容视图。 但是我所说的 bindingcontext 不能从 contentview 内部访问:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Universal_ONE.MyView1"
x:Name="MyView1Name">
<Frame BackgroundColor="#385C6C"
Padding="0,0">
<ImageButton Source="outline_menu_white_24.png"
Command="{Binding Source={x:Reference MyView1Name},Path=PresentMenu}}"
WidthRequest="24"
HeightRequest="24"
Margin="15,0"
BackgroundColor="Transparent"
HorizontalOptions="StartAndExpand" />
</Frame>
</ContentView>
我也这样试过:
<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">
<ImageButton Source="outline_menu_white_24.png"
Command="{Binding PresentMenu}"
WidthRequest="24"
HeightRequest="24"
Margin="15,0"
BackgroundColor="Transparent"
HorizontalOptions="StartAndExpand" />
</Frame>
</ContentView>
我在 PresentMenu 上遇到的错误:未找到绑定 PresentMenu 的 DataContext
如何访问我的内容视图中的 bindingcontext? 如果还不清楚,则内容视图位于单独的文件中。
编辑: 导航栏视图模型:
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; }
}
编辑 2: 我已添加:
x:DataType="viewmodels:Navbarviewmodel
对于两个 contentviews,这消除了它没有 DataContext 的错误。但是,绑定仍然不起作用。
工作解决方案: 我现在已将 viewmodel 添加为 app.xaml 中的静态资源,并在包括用户控件在内的任何地方重用它。我希望在未来的某个时候再看一遍。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。