John Tan
John Tan

Reputation: 1385

Showing the mouse position on a popup

In the XAML I created a popup:

<Popup Name="PopupWindow" Placement="Mouse" IsOpen="False" StaysOpen="False" Opened="PopupWindow_Opened">
    <Border Width="100" Height="100" Background="AntiqueWhite">
        <Label Name="myLabel" Content="Hello World!" />
    </Border>
</Popup>

In the code behind, in the OnMouseClick() event handler:

var position = e.GetPosition(mainPanel);
PopupWindow.IsOpen = true;

However I do not know how to get a reference to myLabel in order to update the value, since it is created inside the XAML directly.

Upvotes: 0

Views: 138

Answers (2)

Noam M
Noam M

Reputation: 3164

You can use x:Name instead of Name and then refer your object like so

XAML

<Popup Name="PopupWindow" Placement="Mouse" IsOpen="False" StaysOpen="False" Opened="PopupWindow_Opened">
    <Border Width="100" Height="100" Background="AntiqueWhite">
        <Label x:Name="myLabel" Content="Hello World!" />
    </Border>
</Popup>

C#

var position = e.GetPosition(mainPanel);
this.myLabel.Content = position.ToString();

x:Name is a xaml concept, used mainly to reference elements. When you give an element the x:Name xaml attribute, "the specified x:Name becomes the name of a field that is created in the underlying code when xaml is processed, and that field holds a reference to the object." (MSDN) So, it's a designer-generated field, which has internal access by default.

Name is the existing string property of a FrameworkElement, listed as any other wpf element property in the form of a xaml attribute.

More about the subject:

Differentiate between x:Name and Name in Wpf application

Upvotes: 1

mm8
mm8

Reputation: 169200

You could do some casting:

Border border = PopupWindow.Child as Border;
Label label = border.Child as Label;
label.Content = "...";

Upvotes: 1

Related Questions