WPF:样式中绑定自定义依赖属性遇Unset值问题
解决WPF样式中绑定自定义附加属性到值转换器的问题
你的问题出在两个地方:附加属性的绑定路径写法错误,以及RelativeSource的选择不当,导致无法正确获取到FieldId的值。
修正步骤
1. 修正绑定路径与RelativeSource
将Style中MultiBinding的第二个Binding修改为以下写法:
<Binding Path="(local:FieldName.FieldId)" RelativeSource="{RelativeSource Self}" />
- 附加属性的绑定路径必须用括号包裹,WPF才能识别这是一个附加属性,而非普通的CLR属性。
- 使用
RelativeSource Self直接指向当前应用样式的TextBox实例,避免用AncestorType带来的上下文查找问题(在Style的Setter上下文里,Ancestor查找可能无法正确定位到目标元素)。
2. 确认自定义附加属性定义正确
确保你的FieldName附加属性是标准的注册方式,示例代码如下:
public static class FieldName { // 注册附加属性 public static readonly DependencyProperty FieldIdProperty = DependencyProperty.RegisterAttached( "FieldId", typeof(string), typeof(FieldName), new PropertyMetadata(null)); // Setter方法 public static void SetFieldId(DependencyObject element, string value) { element.SetValue(FieldIdProperty, value); } // Getter方法 public static string GetFieldId(DependencyObject element) { return (string)element.GetValue(FieldIdProperty); } }
修正后的完整XAML
<Window.Resources> <local:Conv x:Key="MyConv" /> <Style x:Key="TextBoxField" TargetType="{x:Type TextBox}"> <Setter Property="DataContext"> <Setter.Value> <MultiBinding Converter="{StaticResource MyConv}"> <Binding RelativeSource="{RelativeSource AncestorType={x:Type Window}}" /> <Binding Path="(local:FieldName.FieldId)" RelativeSource="{RelativeSource Self}" /> </MultiBinding> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> <TextBox local:FieldName.FieldId="FirstName" Style="{StaticResource TextBoxField}"/> </Grid>
这样修改后,转换器就能正确接收到Window实例和FieldId的"FirstName"值了。
内容的提问来源于stack exchange,提问作者Seated
相关产品推荐
相关产品推荐

