将组合框文本绑定到另一个组合框中的ValidationRule ?



我想将ComboBox CB1中的文本绑定到ComboBox CB2中的验证规则(CommunicationMode)。我的源代码看起来是这样的,但是我得到了错误:"Binding"只能为"dependencyproperty"设置。一个"DependencyObject"有办法解决这个问题吗?

public string CommunicationMode { get; set; }

public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
return new ValidationResult(true, null);
}

<ComboBox Name="CB1">
<ComboBox.Text>
<Binding Path="CB1" UpdateSourceTrigger="PropertyChanged"/>
</ComboBox.Text>
</ComboBox>
<ComboBox Name="CB2">
<ComboBox.Text>
<Binding Path="CB2" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<valid:ComboboxValidationRule CommunicationMode="{Binding ElementName=CB1, Path=Name}" ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</ComboBox.Text>
</ComboBox>

您可以创建一个具有依赖属性的Wrapper类:

public class ComboboxValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
//your validation logic...
return new ValidationResult(true, null);
}
public Wrapper Wrapper { get; set; }
}
public class Wrapper : DependencyObject
{
public static readonly DependencyProperty CommunicationModeProperty =
DependencyProperty.Register(nameof(CommunicationMode), typeof(string), typeof(Wrapper));
public string CommunicationMode
{
get { return (string)GetValue(CommunicationModeProperty); }
set { SetValue(CommunicationModeProperty, value); }
}
}

XAML:

<ComboBox Name="CB2">
<ComboBox.Text>
<Binding Path="CB2" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<valid:ComboboxValidationRule ValidatesOnTargetUpdated="True">
<valid:ComboboxValidationRule.Wrapper>
<valid:Wrapper CommunicationMode="{Binding Source={x:Reference CB1}, Path=Name}" />
</valid:ComboboxValidationRule.Wrapper>
</valid:ComboboxValidationRule>
</Binding.ValidationRules>
</Binding>
</ComboBox.Text>
</ComboBox>

相关内容

  • 没有找到相关文章

最新更新