我正在创建一个具有 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); }
}
在这里我设置了
BorderColor
的SelectionFrame
: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/