我的WPF用户控件有单向绑定,我不知道为什么

时间:2013-03-04 21:14:59

标签: c# wpf data-binding user-controls

我创建了一个非常简单的用户控件,显示ColorPicker(来自WPF扩展工具包)和十六进制代码的文本字段:

<UserControl x:Class="HexColorPicker"> <!-- namespace declarations omitted -->
    <UserControl.Resources>
        <glue:ColorToRgbHex x:Key="colorToHex"/> <!-- custom converter I made -->
    </UserControl.Resources>
    <StackPanel Orientation="Horizontal" Name="layoutRoot">
        <Label Content="#"/>
        <TextBox Text="{Binding SelectedColor, Converter={StaticResource colorToHex}}"/>
        <extToolkit:ColorPicker SelectedColor="{Binding SelectedColor}"/>
    </StackPanel>
</UserControl>

以下是支持代码:

public partial class HexColorPicker : UserControl
{
    public static readonly DependencyProperty SelectedColorProperty
        = DependencyProperty.Register("SelectedColor", typeof(Color), typeof(HexColorPicker));

    public HexColorPicker()
    {
        InitializeComponent();
        layoutRoot.DataContext = this;
    }

    public Color SelectedColor
    {
        get { return (Color)GetValue(SelectedColorProperty); }
        set { SetValue(SelectedColorProperty, value); }
    }
}

layoutRoot.DataContext恶作剧来自this place I found

然后我就像那样使用我的控件:

<me:HexColorPicker SelectedColor="{Binding MyColor}"/>

它有点奏效。文本字段和颜色选择器是同步的:当一个更改时,另一个也会更改。但是,控件和模型对象不是双向同步的:如果我更改模型对象的MyColor属性,我的控件将更新,但是当我使用my更改它时,MyColor属性将不会更新控制。

我做错了什么?为什么从我的模型单向绑定到我的控制?

2 个答案:

答案 0 :(得分:3)

将您的DependencyProperty声明更改为:

public static readonly DependencyProperty SelectedColorProperty = DependencyProperty.Register("SelectedColor", typeof (Color), typeof (HexColorPicker), new FrameworkPropertyMetadata(default(Color),FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

答案 1 :(得分:0)

我记得,在类型之间转换的绑定有时默认为OneWay绑定。

来自BindingMode.Default(http://msdn.microsoft.com/en-us/library/system.windows.data.bindingmode.aspx)的参考:

  

使用绑定目标的默认模式值。每个依赖项属性的默认值都不同。通常,用户可编辑的控件属性(例如文本框和复选框的属性)默认为双向绑定,而大多数其他属性默认为单向绑定。确定依赖项属性是默认绑定单向还是双向的一种编程方法是使用GetMetadata获取属性的属性元数据,然后检查BindsTwoWayByDefault属性的布尔值。

看起来问题是您的控件不被视为“用户可编辑”控件。

最简单的解决方案是在绑定中指定Mode=TwoWay

相关问题