Accessing object in referenced xaml file
-
03-07-2021 - |
Question
I have a project (c#, wpf) and I'm referencing to a Lib that contains another xaml-file (other namespace of course). Then I'm creating an object of a class defined in the Lib:
DialogStandard newWindow = new DialogStandard();
newWindow.Title = "my title";
newWindow.mainLabel.Content = "my label";
DialogStandard is of type window (of course with objects defined in xaml)
public partial class DialogStandard : Window
I'm able to access the Title (newWindow.Title = "my title") because Title is an attribute of class Window. But I can't access mainLabel because that is defined in xaml file of DialogStandard:
<Label Margin="5,5,0,10" Name="mainLabel" VerticalAlignment="Center"/>
How can I make objects defined in xaml-file of DialogStandard accessible to the project where I'm referencing to the Lib where DialogStandard is defined?
Solution
The easiest way to get your Label
if it has Name
with the help of the FrameworkElement.FindName method:
DialogStandard newWindow = new DialogStandard();
newWindow.Title = "my title";
Label mainLabel = (Label)newWindow.FindName("mainLabel");
mainLabel.Content = "my label";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow