How to add an event to a Trailing Icon on textbox? #3142
-
Hello, I want to open file dialog when I click the trailing icon, what should i do?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@MatthewGuo93 Currently I don't think you have built-in options for doing that. I guess it could be worth creating an attached event So if you want to "solve" your problem right now, you would probably need to resort to something like the handling the Disclaimer: This approach is very hacky, and relies on knowledge of the MDIX style involved; in other words, use with caution, and at your own risk. <TextBox materialDesign:HintAssist.Hint="Result directory"
materialDesign:TextFieldAssist.HasTrailingIcon="True"
materialDesign:TextFieldAssist.TrailingIcon="Folder"
PreviewMouseDown="TextBox_OnPreviewMouseDown"/> private void TextBox_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
TextBox textBox = (TextBox) sender;
var icon = textBox.FindChild<PackIcon>("TrailingPackIcon");
if (icon is { IsMouseOver: true })
{
// Trailing icon clicked, do the stuff...
}
} This last part is simply "stolen" from an internal helper class; you may already have similar helper methods available to you. internal static class TreeHelper
{
public static T? FindChild<T>(this DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T? foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
if (child is not T)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
// If the child's name is set for search
if (child is FrameworkElement frameworkElement && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
} |
Beta Was this translation helpful? Give feedback.
@MatthewGuo93 Currently I don't think you have built-in options for doing that.
I guess it could be worth creating an attached event
TextFieldAssist.TrailingIconClicked
which could be invoked when the icon is clicked. This could be "wired up" when theTextFieldAssist.HasTrailingIcon
is set. Anyways this will require changes in the library and does not help you out right now.So if you want to "solve" your problem right now, you would probably need to resort to something like the handling the
PreviewMouseDown
event (or similar) and then inspecting if the mouse is currently over the icon.Disclaimer: This approach is very hacky, and relies on knowledge of the MDIX style involved; in other w…