我正在尝试绑定一个附加属性Entry
控制它的根父级的属性,它是ContentView
:
(主要是使用/访问被调用视图的ViewModel(BindingContext)NumBehaviors
班级)
应用程序在启动之前就崩溃了,而调试中没有明确的问题点:
由于对象的当前状态,操作无效。
在 D:\a\1\s\Xamarin.Forms.Core\ 中的 Xamarin.Forms.Binding.ApplyRelativeSourceBinding (Xamarin.Forms.BindableObject targetObject, Xamarin.Forms.BindableProperty targetProperty) [0x00041]绑定.cs:153 https://github.com/xamarin/Xamarin.Forms/blob/17881ec93d6b3fb0ee5e1a2be46d7eeadef23529/Xamarin.Forms.Core/Binding.cs#L153
[错误] 致命未处理异常:System.InvalidOperationException:由于对象的当前状态,操作无效。
1-我做错了什么吗(也许是BindingContext
)?或者 Xamarin 仍然不能像 wpf 那样处理绑定(比如缺少ElementName
) ?
2-为什么调试错误/异常不那么明确?
MainView.xaml:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:Helpers="clr-namespace:App.Helpers"
xmlns:Behaviors="clr-namespace:App.Behaviors"
HorizontalOptions="FillAndExpand"
VerticalOptions="Center"
x:Class="App.Views.MainView">
<Entry>
<Entry.Behaviors>
<Behaviors:NumBehaviors Helpers:HelperClass.Vm=
"{Binding Source={RelativeSource AncestorType={x:Type ContentView}}, Path=VM}"/>
</Entry.Behaviors>
</Entry>
HelperClass.cs
public static BindableProperty VmProperty =
BindableProperty.Create("Vm", typeof(object), typeof(HelperClass), null);
public static object GetVm(BindableObject bindable)
{
return (object)bindable.GetValue(VmProperty);
}
public static void SetVm(BindableObject bindable, object value)
{
bindable.SetValue(VmProperty, value);
}
MainView.cs
public object VM {get; set;}
public MainView()
{
InitializeComponent();
VM = (object) new MyViewModel();
BindingContext = VM;
}
NumBehaviors.cs
...
void OnEntryTextChanged(object sender, TextChangedEventArgs args) {
var usedvm = HelperClass.GetVm((BindableObject)sender);
}
我也许可以使用以下内容,但我认为这是一个坏主意,当BindingContext
of Entry
与它的根父级不同,它看起来也不灵活:
...
void OnEntryTextChanged(object sender, TextChangedEventArgs args) {
var usedvm = ((Entry)sender).BindingContext;
}
附:
也许我的方法不好,我愿意接受更好的方法来实现这一目标。
EDIT
Using Xamarin.Forms 4.8.0.1364
还尝试过AncestorType={x:Type local:MainView}}
代替AncestorType={x:Type ContentView}}
给出了相同的结果。
也许这与 Xamarin.Forms 的这个开放问题有关[Bug] 使用 AncestorType 时编译的绑定不起作用 #9839 https://github.com/xamarin/Xamarin.Forms/issues/9839