WinUI3中如何通过代码获取Style里Setter设置的DependencyProperty值
WinUI3中获取Style Setter设置的依赖属性值解决方案
1. 等待元素加载完成后获取属性值
Style的Setter值要在元素添加到可视化树并完成加载后才会生效,直接在创建Button后获取会拿到默认值或触发异常。需在Loaded事件中处理:
var button = new Button(); button.Style = (Style)Application.Current.Resources["NodeStyle"]; button.Loaded += (sender, e) => { // 直接从Button实例获取生效后的属性值 double height = button.Height; CornerRadius cornerRadius = button.CornerRadius; Brush background = button.Background; // 后续逻辑处理 }; // 务必将Button添加到可视化树 YourContainerPanel.Children.Add(button);
2. 遍历Style Setters时正确解析属性与值
不要依赖Property.GetMetadata(typeof(Button)).DefaultValue——Setter设置的是样式生效后的属性值,而非依赖属性的默认值。直接通过setter.Property匹配目标依赖属性,转换setter.Value的类型即可:
var nodeStyle = (Style)Application.Current.Resources["NodeStyle"]; foreach (Setter setter in nodeStyle.Setters) { if (setter.Property is not DependencyProperty prop) continue; switch (prop) { case Button.HeightProperty: double height = (double)setter.Value; // 处理Height值 break; case Button.CornerRadiusProperty: CornerRadius radius = (CornerRadius)setter.Value; // 处理CornerRadius值 break; case Button.BackgroundProperty: Brush background = (Brush)setter.Value; // 处理Background值 break; // 其他需要处理的属性 } }
3. 解决GetValue抛出COM异常的问题
System.Runtime.InteropServices.COMException (0x8000FFFF)通常是因为元素未添加到可视化树,或样式尚未完成应用。确保:
- 调用
GetValue前已将Button添加到可视化树 - 在
Loaded事件或LayoutUpdated事件中执行属性获取逻辑
4. 处理Setter值为资源引用的情况
如果XAML中Setter使用了StaticResource或DynamicResource,setter.Value会是ResourceReferenceExpression类型,需解析为实际值:
if (setter.Value is ResourceReferenceExpression resourceRef) { object actualValue = Application.Current.Resources[resourceRef.ResourceKey]; // 根据属性类型转换actualValue并处理 }
内容的提问来源于stack exchange,提问作者Eliy Arlev
相关产品推荐
相关产品推荐

