Xamarin.forms can';不要将viewmodel绑定到ResourceDictionary

Xamarin.forms can';不要将viewmodel绑定到ResourceDictionary,xamarin.forms,visual-studio-2019,Xamarin.forms,Visual Studio 2019,我正在尝试在ResourceDictionary中绑定ViewModelBase,以便调用某些属性来设置控件上的属性,例如,我有一个标签,我希望通过ViewModelBase中的一个属性设置其颜色 更新:ResourceDictionary驻留在MyStyles文件夹中,并在启动时被调用,它不驻留在这样的页面中 void LoadStyles() { if (IsASmallDevice()) { MyResources.MergedDictionaries.A

我正在尝试在ResourceDictionary中绑定ViewModelBase,以便调用某些属性来设置控件上的属性,例如,我有一个标签,我希望通过ViewModelBase中的一个属性设置其颜色

更新:ResourceDictionary驻留在MyStyles文件夹中,并在启动时被调用,它不驻留在这样的页面中


void LoadStyles()
{
    if (IsASmallDevice())
    {

       MyResources.MergedDictionaries.Add(SmallDevicesStyle.SharedInstance);
    }
    else
    {

       MyResources.MergedDictionaries.Add(GeneralDevicesStyle.SharedInstance);
    }
}



所以我的问题是,如何在ResourceDictionary中绑定ViewModelBase,以便访问驻留在ViewModelBase中的属性/方法?

您需要为Label设置BindingContext

ViewModelBase:

 public class ViewModelBase
 {
    //public string DefaultBackGroundColor { get; set; } = "Aqua";
    private string BackGroundColor = "Aqua";
    public string DefaultBackGroundColor
    {        
        get { return BackGroundColor; }
    }
}
Xaml:



嗨,Wendy,样式位于我的样式文件夹中的一个单独文件中,在启动时会被调用,因此我不确定这是否会如您所说的那样起作用,这意味着它不是页面的一部分。抱歉有任何误解,我将更新我的帖子。臧,好的,我再次快速反应,你的方法在我的情况下也很有效:-)我将把这篇帖子作为回答抱歉,我刚刚意识到我没有正确地澄清我的答案,我只需在StyleTarget属性中添加以下行,然后就可以访问ViewModel中的所有属性了。
   public class ViewModelBase : BaseViewModel
   {
     sting BackGroundColor = "aqua";
     public string DefaultBackGroundColor { get return BackGroundColor; }
   }

 public class ViewModelBase
 {
    //public string DefaultBackGroundColor { get; set; } = "Aqua";
    private string BackGroundColor = "Aqua";
    public string DefaultBackGroundColor
    {        
        get { return BackGroundColor; }
    }
}
 <ContentPage.Resources>
    <ResourceDictionary>
        <viewModels:ViewModelBase x:Key="BaseView" />
    </ResourceDictionary>
    <Style TargetType="Label">
        <Setter Property="BackgroundColor" Value="{Binding DefaultBackGroundColor}" />
        <Setter Property="BindingContext" Value="{StaticResource BaseView}"></Setter>
    </Style>
 </ContentPage.Resources>
 <ContentPage.Content>
    <StackLayout>
        <Label
            HorizontalOptions="CenterAndExpand"
            Text="Welcome to Xamarin.Forms!"
            VerticalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage.Content>