一、FindName
WPF FindName,后台查找控件Template,布局控件或UserControl内的某个命名控件。
如:
//.xaml
<StackPanel x:Name="stackPanel">
<TextBlock x:Name="dog"/>
<TextBlock x:Name="cat"/>
</StackPanel>
//.cs
object wantedNode = stackPanel.FindName("dog");
if (wantedNode is TextBlock)
{
// Following executed if Text element was found.
TextBlock wantedChild = wantedNode as TextBlock;
wantedChild.Foreground = Brushes.Blue;
}
二、FindResource
后台查找xaml里定义的资源。
//.xaml
...
<Window.Resource>
<SolidColorBrush x:Key="RainbowBrush" Color="#666666"/>
</Window.Resource>
...
//.cs
void SetBGByResource(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
b.Background = (Brush)this.FindResource("RainbowBrush");
}
(注意资源定义的位置)
FindName参考链接:
https://blog.csdn.net/weixin_33921089/article/details/86351887
https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/advanced/how-to-find-an-element-by-its-name?view=netframeworkdesktop-4.8
https://blog.csdn.net/weixin_44543135/article/details/98762476
FindResource参考链接:
https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.frameworkelement.findresource?view=windowsdesktop-8.0#system-windows-frameworkelement-findresource(system-object)
https://zhuanlan.zhihu.com/p/408573769