我做了一个非常简单的Yes/No RadioBox控件。
在其背后的代码中,我具有以下BindableProperty
:
public static readonly BindableProperty SelectedValueProperty = BindableProperty.Create(
"SelectedValue",
typeof(int),
typeof(YesNoView),
0,
BindingMode.TwoWay);
它的属性:
public int SelectedValue
{
get { return (int) GetValue(SelectedValueProperty); }
set { SetValue(SelectedValueProperty, value); }
}
此属性在ContentView-XAML中的绑定(bind)方式如下:
<DataTrigger Binding="{Binding SelectedValue}" Value="0" TargetType="Image">
<Setter Property="Source" Value="radiobutton_checked.png" />
</DataTrigger>
每当我在某些Page中使用ContentView并将
SelectedValue
设置为恒定值时,一切正常!但是,当我使用
{Binding SomeValue}
而不是常量值(其中SomeValue
是我正在使用ContentView的页面上的一个属性(带有notify))时,它只会拒绝执行任何操作。每当我将SomeValue
设置为某个值时,它就永远不会到达ContentView,并且让我发疯,为什么它不起作用。即使当我调整BindableProperty来指定一个propertyChanged事件时,也永远不会触发该事件,除非我在Xaml中恢复为恒定值而不是绑定(bind)。
谁能阐明为什么会这样并且没有按我预期的那样工作?
编辑:我应该在页面和 View 中都将BindingContext设置为此。
最佳答案
我一共浪费了4个小时才弄明白了...
切勿在ContentView中使用BindingContext = this;
,因为它会从Page劫持上下文,试图对其进行数据绑定(bind)。而是使用Content.BindingContext = this;