Replies: 2 comments 2 replies
|
I got a similar issue, it was resolved using ReflectionBinding instead of Binding. HTH |
1 reply
|
I do not try it, but maybe the fact that MainWindow's DataContext is set via XAML with MainViewModel is the reason why your FooUserControl's DataContext is also initially set to this MainViewModel. And only after that FooUserControl's DataContext binding take effect, so you app continues to run normally I haven't encountered such errors, even though I use a similar methods for passing ViewModels. However, I never expose ViewModels via XAML Try to remove from MainWindow <Window.DataContext>
<viewModels:MainViewModel/>
</Window.DataContext>And set Window DataContext from code (probably in OnFrameworkInitializationCompleted() mathod of App class) |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I have a
MainWindowwhoseDataContextis set to aMainViewModel. TheMainViewModelexposes aSubViewModelproperty. I want to pass thisSubViewModelas theDataContextof a childFooUserControl, so that the control can bind to properties onSubViewModelusing its own compiledx:DataType.Here is the setup:
MainViewModel & SubViewModel:
MainWindow.axaml — the Window has
x:DataType="MainViewModel"and passesSubViewModelto the child control viaDataContext="{Binding Path=SubViewModel}":FooUserControl.axaml — the child control declares
x:DataType="SubViewModel"and binds{Binding Name}:When
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>is set in the.csproj, the application throws the following exception once during startup:The exception occurs inside the compiled binding generated getter for the child control:
It appears that during initialization the compiled binding passes the parent's
DataContext(MainViewModel) into theFooUserControl's getter before the child's ownDataContextbinding ({Binding Path=SubViewModel}) has taken effect, causing the cast to fail.After this one-time exception, the application continues to run normally and the bindings work as expected.
My question: Is this a bug in the compiled bindings system, or am I using
DataContext="{Binding Path=SubViewModel}"incorrectly withx:DataTypeon the child control? If there is a recommended pattern for passing a sub-viewmodel to a child control'sDataContextwhen compiled bindings are enabled, I'd appreciate any guidance.All my code is in github: https://gitlab.gz.cvte.cn/lindexi/InternalCode/tree/ff3f7aa8c453924511f49f07748a786ff47fc52e/AvaloniaIDemo/LajaidemdawHalwelrearkea
I can repro in Avalonia 12.0.3
All reactions