绑定到 UserControl 的 属性

Binding to a Property of UserControl

我写了一个包含很多东西的小部件,它包含一个正在从 UC class 内部更新的 属性 (DependencyProperty)(基于输入到文本框中的输入和来自按钮点击等的输入。)它的定义是:

public partial class UserControlClassName : UserControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    } 

    public static readonly DependencyProperty ValueProperty = System.Windows.DependencyProperty.Register("Value", typeof(string), typeof(UserControlClassName), new PropertyMetadata(string.Empty, OnValueChanged));

    public string Value
    {
        get { return (string)GetValue(ValueProperty); }
        set 
        { 
            SetValue(ValueProperty, value);
            NotifyPropertyChanged("Value");
        }
    }

    private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue != null && e.NewValue != e.OldValue)
        {
            Console.Out.WriteLine("new value: " + e.NewValue);
        }
    }

   ...
   ...
   lots of other code that updates the Value property..
   ...
   ...

}

我在一些 window 的 XAML 中实例化 UC,如下所示:

<GeneralControls:UserControlClassName
            x:Name="someRandomName"
            Value="{Binding MyViewModel.MyBoundedValueField, StringFormat=N2, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource DebugBinding}}"
            VerticalAlignment="Bottom" />

为了完成图片,这是视图模型的 属性 我正在使用 "grab" 值 :

public string MyBoundedValueField
    {
        get { return myBoundedValueField; }
        set
        {
            if (myBoundedValueField!= value)
            {
                myBoundedValueField = value;
                OnPropertyChanged("MyBoundedValueField");
            }
        }
    }

我的问题是 - 用户控件 do 中的值 属性 得到更新,但我绑定到的外部 属性 xaml (myBoundedValueField) 没有得到更新.. 绑定到这个依赖项的东西 属性 不工作 - 所以我附加了一个转换器来调试这个并且转换器没有被调用所以它绝对是一个错误的绑定设置..

(Tnx to any1 who help!)

最终的解决方案是添加 Mode=TwoWay

<GeneralControls:UserControlClassName
    x:Name="someRandomName"
    Mode=TwoWay
    Value="{Binding MyViewModel.MyBoundedValueField, StringFormat=N2, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource DebugBinding}}"
    VerticalAlignment="Bottom" />

我不知道为什么绑定在没有它的情况下无法工作 - 我很想听听解释,如果任何 1 可以遮挡一些光线..

特别感谢@Clemens!!!