我需要使用我ModelView中的“ModelView”列表
<TextBox Grid.Row="2" Grid.Column="0"
Style="{StaticResource StyleTxtErr}"
Validation.ErrorTemplate="{StaticResource ValidationGrp}"
>
<TextBox.Text>
<Binding Path="sGrp" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:cDataGrpRule lFx="{Binding lFx}"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>实际上,这段代码在“
绑定不能设置为lFx,
绑定只能设置为DependencyProperty的DependenxyObject
如何使用设置在我的ValidationRule中的对象来初始化我的ViewModel对象?
提前谢谢。埃里克。
发布于 2021-08-12 10:59:20
由于您只能绑定到依赖项属性,正如错误消息所解释的那样,您应该创建一个从DependencyObject派生并公开依赖属性的包装类。
您还需要一个捕捉当前DataContext的代理对象。
public class BindingProxy : Freezable
{
protected override Freezable CreateInstanceCore() => new BindingProxy();
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy),
new PropertyMetadata(null));
}然后将一个CLR属性添加到ValidationRule类中,该类返回此包装器类型的实例:
public class cDataGrpRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
//your validation logic...
return ValidationResult.ValidResult;
}
public Wrapper Wrapper { get; set; }
}
public class Wrapper : DependencyObject
{
public static readonly DependencyProperty lFxProperty =
DependencyProperty.Register("lFx", typeof(object), typeof(Wrapper));
public object lFx
{
get { return GetValue(lFxProperty); }
set { SetValue(lFxProperty, value); }
}
}您可能想要考虑重命名属性以符合C#命名约定。
XAML:
<TextBox Grid.Row="2" Grid.Column="0"
Style="{StaticResource StyleTxtErr}"
Validation.ErrorTemplate="{StaticResource ValidationGrp}">
<TextBox.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding}"/>
</TextBox.Resources>
<TextBox.Text>
<Binding Path="sGrp" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:cDataGrpRule>
<local:cDataGrpRule.Wrapper>
<local:Wrapper lFx="{Binding Data.lFx, Source={StaticResource proxy}}"/>
</local:cDataGrpRule.Wrapper>
</local:cDataGrpRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>有关更多信息和完整示例,请参阅这篇文章。
https://stackoverflow.com/questions/68755674
复制相似问题