【发布时间】:2009-10-30 09:26:40
【问题描述】:
我有一个在DataTemplate 中使用的用户控件,这个UserControl 包含一个TextBox,它与我的Value 属性(声明为DependencyProperty)绑定UserControl。在数据模板中,我将此 Value 属性与我的实际属性绑定,例如 Name(也是 DependencyProperty)。它工作正常,我在加载时为 Name 属性分配了一个值,我的 TextBox 显示它,我从 TextBox 更改值,它也更新了我的 Name 属性.
现在问题来了,当我在依赖属性中添加 PropertyChangedEventHandler 时,我检查该值是否有效,如果有效则不执行任何操作,如果无效则分配旧值。如果值无效,当我为其分配旧值时,属性会更新,但它不会在我的TextBox 或UserControl 中显示更新的值。谁能告诉我为什么?
XAML 我的UserControl:
<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 属性一个PropertyChangedCallback 到myClass 中我的Name 属性,执行一些验证并在验证失败时重新分配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
}
【问题讨论】:
-
没有看到您的代码,这将是一个很难正确评论的问题。你能把你的代码贴出来吗?
-
太多了,发不出去。您可以询问是否需要更多解释。
-
不,你可以编写最少的代码片段来重现......否则,我们将猜测,而不是回答。没有人喜欢不确定性。尤其是程序员..
标签: wpf xaml textbox user-controls datatemplate