I have some UserControls in my project like pnlCanvas and pnlTools.
There are several buttons in pnlTools like "Add Circle", "Add Rectangle", "Add Text", ...
When the user clicks on one of the buttons, an element sould be added to the childrens of the Canvas (cnvsObjects) which is located in the pnlCanvas.
My MainWindow.xaml is like this:
<Window x:Class=...>
<Grid>
...
<local:pnlCanvas Grid.Column="2"/>
<GridSplitter Grid.Column="3" HorizontalAlignment="Stretch"/>
<local:pnlTools Grid.Column="4" />
...
</Grid>
</Window>
The pnlCanvas.xaml:
<UserControl x:Class=...>
<GroupBox>
<GroupBox.Header...>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Canvas x:Name="cnvsObjects" Width="1920" Height=...>
</Canvas>
</ScrollViewer>
</GroupBox>
</UserControl>
The pnlTools.xaml:
<UserControl x:Class=...>
<GroupBox>
<GroupBox.Header...>
<StackPanel>
<Button Content="Add Text" Click="Button_Click"></Button>
<Button Content="Add Rectangle"></Button>
<Button Content="Add Line"></Button>
...
</StackPanel>
</GroupBox>
</UserControl>
The pnlTools.xaml.cs:
....
public partial class pnlTools : UserControl
{
public pnlTools()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
TextBlock tb = new TextBlock();
tb.TextWrapping = TextWrapping.Wrap;
tb.Margin = new Thickness(10);
tb.Text = "A Text as Test";
cnvsObjects.Children.Add(tb); // Error!
}
}
}
As I've searched, I know in such cases I should use something like Dependency Properties. If it would have been a TextBlock, I could use Data Binding and a Dependency Property. But it is not a Property but a Method (Children.Add).
I'm new in WPF, so if All of things were in the MainWindow.Xaml, I had no problem. I have devided the MainWindos.xaml into some UserControls (nesting) to decrease the complexity and avoid a file to become huge. Did I choose UserControl for that purpose right? or should I use something else? What is the best way of doing that?
Sorry that this post became too long. I couldn't analyse other questions and answers related to this problem because they were so complex for me. Thanks.