【发布时间】:2013-03-30 12:55:44
【问题描述】:
我遇到了绑定问题。由于RelativeSource 需要视觉树向上移动并找到所需的祖先,因此您只能在UIElement 上使用它,但我正在尝试对非UIElement 进行RelativeSource 绑定,例如ValidationRule,众所周知,它既不在VisualTree 内,也不在UIElement 内。正如您所料,绑定中断。找不到RelativeSource,因为就像我说的,没有可用的VisualTree 或LogicalTree。不过我需要让它工作。
这是 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,因此我必须创建一个派生自 DependencyObject 的类,称为 DepObjClass,以便能够写下 xaml 绑定表达式。
代码如下:
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 绑定表达式编译的原因。
当我运行应用程序时,绑定本身不起作用,因为无法找到 StackPanel,因为 ValidationRule 没有 VisualTree,我的验证规则也没有参与逻辑或可视树。
问题是我如何使这种情况起作用,如何从非 UIElement(例如我的 ValidationRule)中找到 StackPanel?
我为我的代码没有编译而道歉,但我希望你能理解我想要做什么。 我给你们50分的正确答案。
【问题讨论】:
-
也许像this 这样的东西可以提供帮助。
-
您到底想达到什么目的?您的
MyValidationRule类具有DependencyObject类型的属性,但实际上并没有使用它。 -
是的,dependeyobject 有一个依赖属性,我在 xaml 中绑定,但绑定 aint 工作,因为在 visualtree 上,因为验证本身不参与 visualtree,所以我如何使它工作
-
我的意思是你要解决什么问题?为什么需要在验证规则中进行绑定?
-
@dowhilefor 有那些树解决方案,但它们似乎非常“以某种方式调整它以使其工作”。