简体   繁体   English

将 object 分配给 ResourceDictionary 中的 BindableProperty

[英]Assign an object to a BindableProperty in ResourceDictionary

I try to initialize and assign an instance of a custom class to a BindableProperty in a ResourceDictionary (styles.xaml).我尝试初始化自定义 class 的实例并将其分配给ResourceDictionary (styles.xaml) 中的BindableProperty

My class:我的 class:

namespace Foo {
  public class Colors {
    public Color Positive { get; set; }
    public Color Negative { get; set; }
    public Color Neutral { get; set; }

    public Colors() { }
  }
}

My class with BindableProperty:我的 class 带有 BindableProperty:

namespace Foo {
  public class Bar : ContentView {
    public Colors Colors {
      get => (Colors)GetValue(ColorsProperty);
      set => SetValue(ColorsProperty, value);
    }

   public static BindableProperty ColorsProperty = 
            BindableProperty.Create(nameof(Colors), typeof(Colors), 
            typeof(Bar), null, BindingMode.OneWay);

styles.xaml styles.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    xmlns:foo="clr-namespace:Foo;assembly=Foo">
  <foo:Colors
        x:Key="colors"
        Positive="Green"
        Negative="Red"
        Neutral="Blue"/>

  ...

  <Style TargetType="foo:Bar">
    <Setter Property="Colors" Value="{StaticResource colors}"/>
  </Style>
</ResourceDictionary>

A breakpoint in the constructor of class Foo.Colors is hit, so an instance of this class is created during loading styles.xaml. A breakpoint in the constructor of class Foo.Colors is hit, so an instance of this class is created during loading styles.xaml. However loading styles.xaml crashes with an unhandled NullReferenceException inside Mono.Android.但是加载 styles.xaml 会崩溃,并在 Mono.ZE84E30B9390CDB664DDB6DB2.C 中出现未处理的NullReferenceException When i delete the assignment of the Color-Property everything works fine, so the assignment must be the problem.当我删除颜色属性的分配时,一切正常,所以分配一定是问题所在。

Any suggestions?有什么建议么?

Exception Details:异常详情:

System.NullReferenceException: Object reference not set to an instance of an object.
  at Android.Runtime.JNINativeWrapper._unhandled_exception (System.Exception e) [0x0000e] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:12 
  at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPL_V (_JniMarshal_PPL_V callback, System.IntPtr jnienv, System.IntPtr klazz, System.IntPtr p0) [0x0001d] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:111 
  at (wrapper native-to-managed) Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPL_V(intptr,intptr,intptr)

The Exception occures in App.xaml.g.cs, after global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(App)); The Exception occures in App.xaml.g.cs, after global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(App));

I found a simple solution that works for me:我找到了一个适合我的简单解决方案:

In styles.xaml I replaced StaticResource with DynamicResource :在 styles.xaml 我用DynamicResource替换了StaticResource

<Style TargetType="foo:Bar">
  <Setter Property="Colors" Value="{DynamicResource colors}"/>
</Style>

Thanks for all suggestions!感谢所有建议!

It looks like you're wanting to use a stand-alone resource dictionary.看起来您想要使用独立的资源字典。 I've had trouble with these in the past when I've followed Microsofts documentation on them.过去,当我遵循 Microsoft 的文档时,我遇到过这些问题。 I've always had to set the dictionary as if it's in another assembly :我总是不得不像在另一个程序集中一样设置字典:

styles.xaml: styles.xaml:

<ResourceDictionary
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:foo="clr-namespace:DELETEME"
    x:Class="DELETEME.styles">

    <foo:Colors
        x:Key="colors"
        Positive="Green"
        Negative="Red"
        Neutral="Blue"/>

    <Style TargetType="foo:Bar">
        <Setter Property="Colors" Value="{StaticResource colors}"/>
    </Style>
</ResourceDictionary>

Note that this file does require a simple code behind:请注意,此文件确实需要一个简单的代码:

namespace DELETEME
{
    public partial class styles : ResourceDictionary
    {
        public styles()
        {
            InitializeComponent();
        }
    }
}

The easiest way to add this file is add a ContentView with xaml, then change the xaml and cs to inherit from ResourceDictionary.添加此文件的最简单方法是添加带有 xaml 的 ContentView,然后将 xaml 和 cs 更改为从 ResourceDictionary 继承。

From there, add the file to the merged dictionaries of the app or page:从那里,将文件添加到应用程序或页面的合并字典中:

<Application xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:foo="clr-namespace:DELETEME"
         x:Class="DELETEME.App">

    <Application.Resources>
       <ResourceDictionary>
           <ResourceDictionary.MergedDictionaries>
               <foo:styles />
           </ResourceDictionary.MergedDictionaries>
       </ResourceDictionary>
    </Application.Resources>
</Application>

This should resolve your errors.这应该可以解决您的错误。 Example below.下面的例子。

Bar.cs class: Bar.cs class:

public class Bar : ContentView
{
    public static readonly BindableProperty ColorsProperty =
        BindableProperty.Create(nameof(Colors), typeof(Colors), typeof(Bar));

    public Colors Colors
    {
        get => (Colors)GetValue(ColorsProperty);
        set => SetValue(ColorsProperty, value);
    }

    public Bar()
    {
        var b1 = new BoxView { BackgroundColor = Colors.Negative };
        var b2 = new BoxView { BackgroundColor = Colors.Neutral };
        var b3 = new BoxView { BackgroundColor = Colors.Positive };

        var sl = new StackLayout();

        sl.Children.Add(b1);
        sl.Children.Add(b2);
        sl.Children.Add(b3);

        Content = sl;
    }
}

MainPage.xaml class:主页.xaml class:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:foo="clr-namespace:DELETEME"
         x:Class="DELETEME.MainPage">

    <StackLayout>
        <foo:Bar />
    </StackLayout>

</ContentPage>

Running Result:运行结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM