WPF-以编程方式更改样式,“找不到样式”

时间:2018-11-02 15:39:34

标签: wpf styles

异常消息:

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代码中找不到我的样式。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

该资源的键只是“ style1”:

newBtn.Style = (Style)FindResource("style1");

您还应该将Style移至<Window.Resources>或在Grid中查找它:

newBtn.Style = theNameOfTheGrid.Resources["style1"] as Style;