DataTemplate
内使用它,这个UserControl
包含一个绑定了Value属性的TextBox
(声明为DependencyProperty
)。在数据模板中,我将这个Value属性与我的实际属性Name(也是DependencyProperty
)绑定。它正常工作,我在加载时给Name属性分配一个值,我的TextBox
显示它,我从TextBox
更改值,它也更新了我的Name属性。现在问题在于,当我在依赖属性中添加一个
PropertyChangedEventHandler
时,我检查该值是否有效,如果有效则不执行任何操作,如果无效则分配旧值。在值无效的情况下,当我分配旧值时,属性会更新,但它不会在我的中的TextBox
中显示更新后的值。有人可以告诉我原因吗?以下是我的的XAML:
<UserControl x:Name="usercontrol">
<StackPanel>
<TextBlock ......./>
<TextBox Binding={Binding ElementName=usercontrol, Path=Value, Mode=TwoWay}/>
</StackPanel>
</UserControl>
在代码后端Value是一个DependencyProperty
我在我的DataTemplate
中使用它:
<HierarchicalDataTemplate DataType="{x:Type myLib:myClass}" ItemsSource="{Binding Children}">
<Expander Header="{Binding}">
<WrapPanel>
<edproperty:TextPropertyEditor Caption="Name" Value="{Binding Name, Mode=TwoWay}"/>
<edproperty:TextPropertyEditor .................../>
<edproperty:TextPropertyEditor .................../>
<edproperty:TextPropertyEditor ...................../>
</WrapPanel>
</Expander>
</HierarchicalDataTemplate>
我正在一个 TreeView
中使用这个模板。在 TreeView
中,我输入值到 TextBox
中,它会更新我的 UserControl
的 Value 属性,然后更新 myClass
的 Name 属性。我为 myClass
的 Name 属性分配了一个 PropertyChangedCallback
,执行一些验证并重新赋值 OldValue
如果验证失败,则更新 Value 属性。但是我仍然看到 TextBox
中有相同的值,而不是更新后的值。
public string Name
{
get
{
return (string)GetValue(NameProperty);
}
set
{
SetValue(NameProperty, value);
}
}
// Using a DependencyProperty as the backing store for Name. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(myClass), new UIPropertyMetadata(null, OnNameChanged));
protected static void OnNameChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
if(checkRequired && !IsValid(e.NewValue.ToString()))
{
checkRequired=false;
(sender as myClass).Name = args.OldValue.ToString();
}
}
private static bool IsValid(string name)
{
.............some logic here
}