WPF 中使用 FindResource 报错 'FindResource 没有定义' 的解决方法
WPF 中使用 FindResource 报错 'FindResource 没有定义' 的解决方法
在 WPF 中,使用 FindResource 方法获取资源时,有时会遇到 'FindResource 没有定义' 的错误。这通常是因为你的类没有继承自 FrameworkElement 或 FrameworkContentElement。
报错代码示例:
var switchButton = new Button
{
Content = '开',
Margin = thickness,
VerticalAlignment = VerticalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center,
Style = (Style)FindResource('butt')
};
switchButton.Click += SwitchButton_Click;
Panel.Children.Add(switchButton);
Grid.SetColumn(switchButton, 11);
解决方法:
-
通过 FrameworkElement 或 FrameworkContentElement 实例来调用该方法:
Style buttStyle = (Style)switchButton.FindResource('butt'); -
将你的类继承自 FrameworkElement 或 FrameworkContentElement:
public class YourClass : FrameworkElement { // your code here }
通过以上两种方法,你就可以在你的类中正确使用 FindResource 方法来获取资源了。
原文地址: https://www.cveoy.top/t/topic/j7DO 著作权归作者所有。请勿转载和采集!