异常消息:
System.Windows.ResourceReferenceKeyNotFoundException:找不到"{StaticResource style1}"资源
C#代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button newBtn = new Button();
newBtn.Height = 30;
//newBtn.Style = Resources["style1"] as Style;
newBtn.Style = (Style)FindResource("{StaticResource style1}");
stackpanel1.Children.Add(newBtn);
}
XAML代码:
<Grid.Resources>
<Style x:Key="style1" TargetType="{x:Type Button}">
.....styleofbutton
</Style>
</Grid.Resources>
<Button Content="Button" HorizontalAlignment="Left" Style="{StaticResource style1}" Margin="128,98,0,0" VerticalAlignment="Top" Width="159" Height="61" Click="Button_Click"/>
<StackPanel x:Name="stackpanel1" HorizontalAlignment="Left" Height="292" Margin="348,72,0,0" VerticalAlignment="Top" Width="395"/>
newBtn在XAML代码中找不到我的样式。我做错了什么?
资源的键只是"style1":
newBtn.Style = (Style)FindResource("style1");
您还应该将Style
移动到<Window.Resources>
,或者在Grid
:中查找它
newBtn.Style = theNameOfTheGrid.Resources["style1"] as Style;