【发布时间】:2013-03-04 21:14:59
【问题描述】:
我创建了一个非常简单的用户控件,它显示了一个 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 属性,我的控件将更新,但当我使用我的控件更改它时,MyColor 属性不会更新。
我做错了什么?为什么从我的模型到我的控件的绑定是单向的?
【问题讨论】:
标签: c# wpf data-binding user-controls