异常消息:
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代码中找不到我的样式。我在做什么错了?
答案 0 :(得分:1)
该资源的键只是“ style1”:
newBtn.Style = (Style)FindResource("style1");
您还应该将Style
移至<Window.Resources>
或在Grid
中查找它:
newBtn.Style = theNameOfTheGrid.Resources["style1"] as Style;