I am getting null when I want to reference UserControl in code behind and using FindControl
XAML:
`<Window xmlns="https://github.com/avaloniaui"
xmlns:local="clr-namespace:AvaloniaApplication1;assembly=AvaloniaApplication1"
MinWidth="500" MinHeight="300">
<local:UserControl1 Name="Ctrl"/>
</Window>`
Code:
`namespace AvaloniaApplication1
{
public class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
App.AttachDevTools(this);
var ctl = this.FindControl<UserControl1>("Ctrl");
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}`
Thanks for the report! This appears to be a problem with named UserControls: seems that becase the UserControl is itself a name scope, the control is getting added to its own name scope and not that of the parent control.
I've been looking into this in WPF and the results are interesting. If I do this (omitting non-relevant attributes etc):
UserControl1.xaml:
<UserControl x:Class="WpfApplication4.UserControl1" Name="foo">
MainWindow1.xaml:
<Window>
<local:UserControl1/>
</Window>
Then foo is added to UserControl1's name scope but not MainWindows.
If however I do this:
UserControl1.xaml:
<UserControl x:Class="WpfApplication4.UserControl1" Name="foo">
MainWindow1.xaml:
<Window>
<local:UserControl1 x:Name="bar"/>
</Window>
Then bar is added to both UserControl1s and MainWindows name scope. I think this is because in WPF simply setting a Name on a control doesn't add it to a name scope: you need to call RegisterName.
I didn't want this behavior in Avalonia because I didn't like the fact that there was different behavior between controls created via XAML and controls created in code, but it seems that the behavior has a use in this case.
We have two options here:
I lean towards 2. though this would cause problems if one were to e.g. include a named UserControl twice in a window.
Most helpful comment
I've been looking into this in WPF and the results are interesting. If I do this (omitting non-relevant attributes etc):
UserControl1.xaml:
MainWindow1.xaml:
Then
foois added toUserControl1's name scope but notMainWindows.If however I do this:
UserControl1.xaml:
MainWindow1.xaml:
Then
baris added to bothUserControl1s andMainWindows name scope. I think this is because in WPF simply setting aNameon a control doesn't add it to a name scope: you need to callRegisterName.I didn't want this behavior in Avalonia because I didn't like the fact that there was different behavior between controls created via XAML and controls created in code, but it seems that the behavior has a use in this case.
We have two options here:
I lean towards 2. though this would cause problems if one were to e.g. include a named
UserControltwice in a window.