2

バインディングに問題があります。RelativeSource上に移動して目的の祖先を見つけるにはビジュアル ツリーが必要なので、それを使用できるのは でのみですが、ValidationRule などの非 UIElement でバインディングUIElementを実行しようとしています。RelativeSourceVisualTreeそのUIElement。ご想像のとおり、バインディングが壊れます。RelativeSource私が言ったように、存在しないVisualTreeLogicalTree利用できないため、見つかりませんでした。私はそれを機能させる必要があります。

XAML の例を次に示します。

<StackPanel DataContext{Binding}>
  <Grid>
    <ContentControl Content{Binding MVPart1>
      <TextBox>
       <TextBox.Text>
        <Binding Path="VMPart1Property1">
         <Binding.ValidationRules>
           <my:MyValidationRule>
            <my:ValidationRule.DOC>
             <my:DepObjClass DepProp={Binding Path=DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}}/>
            </my:ValidationRule.DOC>
          </Binding.ValidationRules>
         </Binding>
       </TextBox.Text>
      </TextBox>  
    </ContentControl>
  </Grid>
</StackPanel>

したがって、基本的に MyValidationRule は ValidationRule クラスから派生していますが、それは UIElement でも DependencyObject でもないため、xaml バインディング式を書き留めるために DepObjClass という DependencyObject から派生するクラスを作成する必要がありました。

コードは次のとおりです。

public class MyValidationRule : ValidationRule
{
  public DepObjClass DOC
  {
    get;
    set;
  }

  public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
  {
      string text = value as string;
      if (!string.IsNullOrEmpty(text))
      {
         return new ValidationResult(true, string.Empty);
      }

      return new ValidationResult(false, "Not working blahhh");
   }
}

public class DepObjClass : DependencyObject
{
  public object DepProp
  {
    get
    {
      return (object)GetValue(DepPropProperty);
    }
    set
    {
      SetValue(DepPropProperty, value);
    }
  }

  public static DependencyProperty DepPropProperty
     = DependencyProperty.Register(typeof(object), typeof(DepObjClass)......);
}

まとめます。MyValidatonRule は UIElement ではなく DependencyObject ではありませんが、タイプのプロパティを持っているため、xaml バインディング式がコンパイルされるのはなぜですか。

アプリケーションを実行すると、ValidationRule に VisualTree がなく、検証ルールが論理ツリーまたはビジュアル ツリーに参加していないため、StackPanel が見つからなかったため、バインディング自体が機能しません。

問題は、そのようなケースを機能させる方法、ValidationRule などの非 UIElement から StackPanel を見つける方法です。

私のコードがコンパイルされていないことをお詫びしますが、私がやろうとしていることを理解していただければ幸いです。正解者には50点差し上げます。

4

1 に答える 1