【发布时间】:2010-03-31 12:03:44
【问题描述】:
我想在我的 wpf 应用程序中使用颜色选择器,我在 this codeproject 页面上看到了一个漂亮的颜色选择器。在我想将控件连接到视图模型之前,该控件可以正常工作。 我用这个视图模型创建了一个小测试程序:
public class ColorViewModel : ViewModelBase
{
public ColorViewModel()
{
LineColor = Brushes.Yellow;
}
SolidColorBrush _brushColor;
public SolidColorBrush LineColor
{
get { return _brushColor; }
set
{
_brushColor = value;
RaisePropertyChanged(() => LineColor);
}
}
}
测试程序有一个文本框和颜色选择器控件:
<StackPanel Orientation="Horizontal">
<TextBlock Text="Please Select a Color" FontWeight="Bold" Margin="10"
Foreground="{Binding Path=LineColor, UpdateSourceTrigger=PropertyChanged}"/>
<vw:ColorPickerControlView x:Name="ForeColorPicker" Margin="10"
CurrentColor="{Binding Path=LineColor, UpdateSourceTrigger=PropertyChanged }"/>
</StackPanel>
在我的测试应用程序主窗口的加载事件中,我将视图模型设置为 datacontext,如下所示:
DataContext = new ColorViewModel();
问题是我似乎无法将视图模型的 LineColor 属性绑定到 ColorPickerControlView 的 CurrentColor 属性。 ColorPickerControlView 的 CurrentControl 属性似乎很好。构造函数如下所示:
public ColorPickerControlView()
{
this.DataContext = this;
InitializeComponent();
CommandBindings.Add(new CommandBinding(SelectColorCommand, SelectColorCommandExecute));
}
在 UserControl 的构造函数中有一行 this.DataContext = this;我读到这是绑定依赖属性所必需的。当我将我的视图模型设置为数据上下文时,我是否会覆盖这一行,这就是我无法绑定到 CurrentColor 属性的原因吗?有什么解决方法吗?还是我又犯了一个错误?
【问题讨论】:
标签: c# wpf data-binding mvvm dependency-properties