Hi,@Michell .Welcome Microsoft Q&A.
In XAML, you could not directly pass constructor parameters when creating an instance of a UserControl. Constructor parameters are typically used to initialize the object and are not directly accessible from XAML.
Instead, you can use Data Binding to pass data to the UserControl from its parent view (e.g., MainWindow).
Here's how you could do it using Data Binding:
NewChart.xaml:
<Grid>
<TextBlock Text="{Binding ChartName}" Width="200" Height="50" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
MainWindowViewModel.cs:
public class MainWindowViewModel
{
public string ChartName { get; set; }
public MainWindowViewModel()
{
ChartName = "Child";
}
}
MainWindow.xaml:
<Window x:Class="WpfApp1.MainWindow"
...
xmlns:local="clr-namespace:WpfApp1"
xmlns:views="clr-namespace:WpfApp1.Views"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<views:MainWindowViewModel x:Key="_instance" />
</Window.Resources>
<StackPanel>
<views:NewChart DataContext="{StaticResource _instance}" />
</StackPanel>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindowViewModel _instance { get; set; }
public MainWindow()
{
InitializeComponent();
_instance = new MainWindowViewModel();
DataContext = _instance;
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.