【问题标题】:Bind ComboBox Text to a ValidationRule inside another ComboBox?将 ComboBox 文本绑定到另一个 ComboBox 内的 ValidationRule?
【发布时间】:2021-11-02 23:15:39
【问题描述】:

我想将 ComboBox CB1 中的文本绑定到 ComboBox CB2 中的验证规则 (CommunicationMode)。 我的源代码看起来像这样,但我收到错误消息:只能为“DependencyObject”的“DependencyProperty”设置“Binding”。 有没有办法解决这个问题?

    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>

【问题讨论】:

  • {Binding ElementName=CB1, Path=Name},绑定不应该在Text而不是Name吗?

标签: c# wpf xaml mvvm binding


【解决方案1】:

您可以创建一个具有依赖属性的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>

【讨论】:

  • @patrickgc:你试过这个吗?如果您的原始问题已经解决,请记住接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 2011-03-08
  • 2012-06-22
  • 2013-10-21
  • 1970-01-01
  • 2021-08-01
相关资源
最近更新 更多