例如前端定制了一个样式:
<!-- banner图片 -->
<Style x:Key="bannerImgStyle" TargetType="Image">
<Setter Property="Width" Value="{Binding Path=ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=local:BannerViewer}}"/>
<Setter Property="Height" Value="{Binding Path=ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=local:BannerViewer}}"/>
<Setter Property="Stretch" Value="Fill"/>
</Style>
那么后端代码的引用方式如下:
void BtnLeft_Click(object sender, RoutedEventArgs e)
{
Style imgStyle = FindResource("bannerImgStyle") as Style;
}
注意!上面的查找资源方式只能在方法和事件里使用,无法定义属性
全局资源样式如下
static readonly Brush BrightBrush = Application.Current.FindResource("Primary") as SolidColorBrush;
static readonly Brush DarkBrush = Application.Current.FindResource("Kerley") as SolidColorBrush;
上面两种色刷资源是全局公共资源,所以从Application.Current中可以查到