c# - 两个 Bindable 属性可以相互通信吗?

标签 c# xamarin mvvm xamarin.forms

我正在创建一个具有 ContentView 的控件(源自 Frame ) field :

public class SelectionFrame : ContentView
{
    Frame f1;
        public SelectionFrame()
        {
            f1 = new Frame
            {
                VerticalOptions = LayoutOptions.Center,
                BackgroundColor = BorderColor,
                HorizontalOptions = LayoutOptions.Center,
                Padding = new Thickness(0),
                CornerRadius = 7,
                HeightRequest = 14,
                WidthRequest = 14,
                Content = f2
            };
            Content = f1;
        }

我设置它的BackgroundColor通过这个BindableProperty :
   public static readonly BindableProperty BorderColorProperty = BindableProperty.Create(nameof(BorderColor), typeof(Color), typeof(SelectionFrame), defaultValue: Color.Black, defaultBindingMode: BindingMode.TwoWay, propertyChanged: ColorChanged);

   public Color BorderColor
        {
            get { return (Color)GetValue(BorderColorProperty); }
            set { SetValue(BorderColorProperty, value); }
        }

然后我在另一个自定义控件( RadioButtonsGroup )中使用这个控件,它有这个 FrontColor BindableProperty :
      public static readonly BindableProperty FrontColorProperty = BindableProperty.Create(nameof(FrontColor), typeof(Color), typeof(RadioButtonsGroup), defaultValue: Color.Black);

  public Color FrontColor
        {
            get { return (Color)GetValue(FrontColorProperty); }
            set { SetValue(FrontColorProperty, value); }
        }

在这里我设置了BorderColorSelectionFrame :
SelectionFrame circle = new SelectionFrame { ClassId = "r", BorderColor = FrontColor, VerticalOptions = LayoutOptions.Center };

我像这样使用控件:
<local:RadioButtonsGroup FrontColor="Red" x:Name="rbs"/>

但是 BackgroundColor框架的颜色没有改变,仍然具有默认颜色(黑色)。

最佳答案

那是因为你没有绑定(bind)BackgroundColor框架的属性到您的自定义控件属性。您在构造函数上设置它,但您没有在监听更改,您在这一行中正在做什么:

SelectionFrame circle = new SelectionFrame { ClassId = "r", BorderColor = FrontColor, VerticalOptions = LayoutOptions.Center };

要更正它,只需将您的 SelectionFrame 构造函数的代码更改为:
public SelectionFrame()
{
    f1 = new Frame
    {
        VerticalOptions = LayoutOptions.Center,
        HorizontalOptions = LayoutOptions.Center,
        Padding = new Thickness(0),
        CornerRadius = 7,
        HeightRequest = 14,
        WidthRequest = 14,
        Content = f2
    };

    f1.SetBinding(Frame.BackgroundColorProperty, new Binding(nameof(BorderColor)));
    f1.BindingContext = this;

    Content = f1;
}

现在您将能够听到对此属性的更改。

我希望它有所帮助。

关于c# - 两个 Bindable 属性可以相互通信吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47772046/

相关文章:

c# - 由于多个依赖项中的相同属性类型导致编译错误

c# - ZXing.NET激光扫描

macos - FxCop 在 Mac - Jenkins 环境中是否兼容?

c# - 在 Xamarin for iOS 中使用 NSTimer 调用 SetNeedsDisplay

wpf - 我应该为我的 View 使用 UserControls 而不是 DataTemplates 吗?

c# - View 在屏幕上时如何修改 XAML 元素的颜色?

c# - LINQ - 包含匿名类型

c# - 我如何弄清楚我需要知道什么?

c# - 如何在 Android 设备上访问/读取/写入内部存储中的文档文件夹?

.net-3.5 - 使用MEF + MVVM照明工具包时组成零件的理想场所?