Reputation: 77
I have a number of buttons in my WPF window and I would like to have certain characters in the button contents underlined.
I have tried using the "_" like "My_Content" to underline the C, however this does not appear until the user hits the Alt key, or has their local settings changed. Using < Underline > within the Content property causes an error when I attempt to underline only part of the content like:
Content="My< Underline >C< /Underline >ontent".
I would prefer to set this in the XAML if possible. Any help would be appreciated.
Thank You!
Upvotes: 6
Views: 8601
Reputation: 1
You can keep the ability to click the button using Alt+Char if you add a binding. In my example I'm using Alt+X to exit(Close) the current window
public class RelayCommand : ICommand
{
private readonly Action _execute;
public event EventHandler CanExecuteChanged;
public RelayCommand(Action execute)
{
_execute = execute;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_execute?.Invoke();
}
}
public partial class Window : Window
{
public ICommand ExitCommand { get; }
public Window()
{
InitializeComponent();
ExitCommand = new RelayCommand(ExitApplication);
CommandBindings.Add(new CommandBinding(ExitCommand, ExecuteExitCommand, CanExecuteExitCommand));
KeyGesture exitKeyGesture = new KeyGesture(Key.X, ModifierKeys.Alt);
InputBindings.Add(new KeyBinding(ExitCommand, exitKeyGesture));
}
private void ExecuteExitCommand(object sender, ExecutedRoutedEventArgs e)
{
ExitApplication();
}
private void CanExecuteExitCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ExitApplication()
{
Close();
}
private void exitbutton_Click(object sender, RoutedEventArgs e)
{
ExitApplication();
}
}
Make sure you also initialize using System.Windows.Input;
Upvotes: 0
Reputation: 41393
You would have to do this explicitly like so:
<Button>
<Button.Content>
<TextBlock>
My <Underline>C</Underline>ontent
</TextBlock>
</Button.Content>
</Button>
This would remove the ability to click the button using Alt+Char though. For that an AccessText element is used. But that doesn't support the markup syntax of TextBlock.
Upvotes: 12