WPF:TextBox文本未更新

vik*_*iky 8 wpf xaml user-controls textbox datatemplate

我有我使用内部的用户控件DataTemplate,这UserControl包含了TextBox其绑定与价值属性(声明为DependencyProperty我的)UserControl.在数据模板中,我将此Value属性与我的实际属性绑定为Name(也是a DependencyProperty).它工作正常,我在加载时为Name属性赋值,我TextBox显示它,我更改了值TextBox,它也更新了我的Name属性.现在问题出现在我PropertyChangedEventHandler在依赖项属性中添加一个,我检查它是否有效的值,如果有效则不执行任何操作,如果无效则分配旧值.在值无效的情况下,当我给它分配旧的价值,性能更新,但它不是在我的显示更新值TextBoxUserControl.谁能告诉我为什么?

我的XAMLUserControl:

<UserControl x:Name="usercontrol">
   <StackPanel>
      <TextBlock ......./>
      <TextBox Binding={Binding ElementName=usercontrol, Path=Value, Mode=TwoWay}/>
   </StackPanel>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

在代码后面,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>
Run Code Online (Sandbox Code Playgroud)

我正在使用的这个模板TreeView.里面TreeView我输入值TextBox,其更新的价值我的财产UserControl,这反过来又更新命名的财产myClass,我分配PropertyChangedCallback到我的名字在房产myClass,执行一些验证和重新分配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
    }
Run Code Online (Sandbox Code Playgroud)

vik*_*iky 8

经过几天的环顾四周和大量的搜索,我找到了解决问题的方法

完成所有验证并分配旧值并更新dependecy属性后,我需要更新UpdateTarget()方法,以更新TextBox中的值.

这就是更好地解释解决方案的原因

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/c404360c-8e31-4a85-9762-0324ed8812ef/