I 开发者_JAVA百科assigned x:Name in my XAML-file to a object which can trigger a MouseDown-event. In that event I'd like to get the x:name-attribute of the sender again. How do I do that?
The object looks like that:
<ModelUIElement3D MouseDown="ModelUIElement3D_MouseDown" x:Name="trololo">
If I have understood your question correctly, you can access the Name
property by casting the sender to a FrameworkElement
.
Alternatively you can just use the reference object that is created by the designer, the instance name is the same as the name that you specify in the x:Name
attribute.
The following demonstrates both options.
private void ModelUIElement3D_MouseDown(object sender, MouseButtonEventArgs e)
{
var element = sender as FrameworkElement;
if (element != null)
{
if (element.Name == "trololo")
{
}
}
// Or
if (sender == trololo)
{
}
}
The FrameworkElement-based Name property is a standard dependency property intended as a shortcut for x:Name (see FrameworkElement.Name Property). However, many dependency objects do not derive from FrameworkElement, and yet they can still use the XAML-attached property x:Name. To determine the x:Name at runtime of an object declared in XAML that does not derive from FrameworkElement, you can retrieve the object's attached property using GetValue, as shown here:
foreach(var column in gridItem.ColumnDefinitions)
{
var name = column.GetValue(FrameworkElement.NameProperty) as string;
if (name == "IsCheckedColumn")
column.Width = show ? CheckUncheckColumn_VisibleWidth : Column_InvisibleWidth;
else if (name == "DeleteColumn")
column.Width = show ? DeleteColumn_VisibleWidth : Column_InvisibleWidth;
}
精彩评论