ContentView中的BindableProperty无法正常工作 [英] BindableProperty in ContentView not working
问题描述
我做了一个非常简单的Yes/No RadioBox控件.
I made a very simple Yes/No RadioBox control.
在其背后的代码中,我具有以下BindableProperty
:
In it's code behind I have the following 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中的绑定方式如下:
This property is bound in the ContentView-XAML using something like this:
<DataTrigger Binding="{Binding SelectedValue}" Value="0" TargetType="Image">
<Setter Property="Source" Value="radiobutton_checked.png" />
</DataTrigger>
每当我在某些Page中使用ContentView并将SelectedValue
设置为恒定值时,一切正常!
Whenever I use my ContentView in some Page and set the SelectedValue
to a constant value, everything works fine!
但是,当我使用{Binding SomeValue}
而不是常量值时,其中SomeValue
是我正在使用ContentView的页面上的一个属性(带有notify),它只会拒绝执行任何操作.每当我将SomeValue
设置为某个值时,它就永远不会到达ContentView,并且让我发疯,为什么它不起作用.
However, when I use a {Binding SomeValue}
instead of a constant value, where SomeValue
is a property (with notify) on the Page I'm using the ContentView on, it will simply refuse to do anything. Whenever I set SomeValue
to some value, it never reaches the ContentView and it's driving me insane why it isn't working.
即使我将BindableProperty调整为也指定一个propertyChanged事件,除非我在Xaml中恢复为恒定值而不是绑定,否则它永远不会触发.
Even when I adjust the BindableProperty to also specify a propertyChanged event, it is simply never triggered unless I revert back to a constant value in the Xaml, rather than a binding.
有人能说明为什么会发生这种情况并且无法按我预期的那样工作吗?
Could anyone shed a light as to why this is happening and not working as I would expect?
我应该在Page和View中都将BindingContext设置为此.
I should add that in both the Page and the View the BindingContext is set to this.
推荐答案
我一共浪费了4个小时才弄明白了...
I figured it out after a total of 4 hours wasted...
请不要在ContentView中执行BindingContext = this;
,因为它会从Page劫持试图将数据绑定到它的上下文.而是使用Content.BindingContext = this;
Never do BindingContext = this;
in your ContentView, as it hijacks the context from the Page trying to databind to it. Instead use Content.BindingContext = this;
这篇关于ContentView中的BindableProperty无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!