问题
I tried to apply a style for my button in the code behind,like this:
using Windows.UI.Xaml.Markup;
MenuButton2.Style = ButtonStyle();
private Style ButtonStyle()
{
string xaml =
"<Style " +
"xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' " +
"xmlns:d = 'http://schemas.microsoft.com/expression/blend/2008' " +
"TargetType='Button'>" +
"<Setter Property='Foreground' Value='#e6e6e6'/>" +
" < Setter Property = 'Template' >" +
" < Setter.Value >" +
"< ControlTemplate TargetType = 'Button' >" +
"< Grid >" +
"< VisualStateManager.VisualStateGroups >" +
"< VisualStateGroup x: Name = 'CommonStates' >" +
"< VisualState x: Name = 'Normal' />" +
"< VisualState x: Name = 'PointerOver' >" +
" < Storyboard >" +
"< ColorAnimation Duration = '0' To = '#e6e6e6' Storyboard.TargetProperty = '(Rectangle.Fill).(SolidColorBrush.Color)' Storyboard.TargetName = 'Button' />" +
"</ Storyboard >" +
"</ VisualState >" +
"< VisualState x: Name = 'Pressed' >" +
" < Storyboard >" +
" < ColorAnimation Duration = '0' To = '#e6e6e6' Storyboard.TargetProperty = '(Rectangle.Fill).(SolidColorBrush.Color)' Storyboard.TargetName = 'Button' />" +
"< ColorAnimation Duration = '0' To = '#e6e6e6' Storyboard.TargetProperty = '(TextBlock.Foreground).(SolidColorBrush.Color)' Storyboard.TargetName = 'Content' />" +
"</ Storyboard > " +
" </ VisualState >" +
" </ VisualStateGroup >" +
" </ VisualStateManager.VisualStateGroups >" +
"< Grid >" +
" < Rectangle x: Name = 'Button' Stroke = 'Transparent' Fill = 'Transparent' Margin = '0' />" +
" < ContentPresenter x: Name = 'Content' />" +
"</ Grid >" +
" </ Grid >" +
"</ ControlTemplate >" +
" </ Setter.Value >" +
" </ Setter >" +
"</Style>";
return (Style)Windows.UI.Xaml.Markup.XamlReader.Load(xaml);
}
but I have a problem when I execute my app,this is the error I get:
An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in App.exe but was not handled in user code WinRT information: illegal qualified name character [Line: 1 Position: 262] Additional information: The text associated with this error code is not found.
thanks for help
回答1:
Is there a particular reason you are trying to do this versus creating a resource dictionary? I have never seen this approach.
Define your Style in a resource dictionary and give it a x:Key="MyStyleName"
Load your dictionary in app.xaml
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Common/StandardStyles.xaml"/>
<ResourceDictionary Source="Common/MyStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
Reference your style anywhere you want:
myStyle = (Style)App.Current.Resource["MyStyleName"];
Use it like: MenuButton2.Style = myStyle;
This would be the more conventional approach to using a syle on your control.
来源:https://stackoverflow.com/questions/34561416/define-a-style-for-a-button-in-code-behind-uwp-app