我想在我的 wpf 应用程序中使用颜色选择器,我在 this codeproject 上看到了一个漂亮的颜色选择器页。在我想将控件连接到 View 模型之前,控件工作正常。 我用这个 View 模型创建了一个小测试程序:
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>
在我的测试应用程序主窗口的加载事件中,我将 View 模型设置为数据上下文,如下所示:
DataContext = new ColorViewModel();
问题是我似乎无法将 View 模型的 LineColor 属性绑定(bind)到 ColorPickerControlView 的 CurrentColor 属性。 ColorPickerControlView 的 CurrentControl 属性似乎没问题。构造函数如下所示:
public ColorPickerControlView()
{
this.DataContext = this;
InitializeComponent();
CommandBindings.Add(new CommandBinding(SelectColorCommand, SelectColorCommandExecute));
}
在 UserControl 的构造函数中有一行 this.DataContext = this;我读到绑定(bind)依赖属性是必要的。当我将 viewmodel 设置为数据上下文时是否覆盖此行,这就是我无法绑定(bind)到 CurrentColor 属性的原因吗?有什么解决方法吗?还是我又犯了一个错误?
最佳答案
您认为 UserControl 的构造函数中的 DataContext=this
短语在绑定(bind)到外部 View 模型时抢占是正确的。在 this question 中进行了讨论.然而,这很容易补救。 xaml 绑定(bind)到的 UserControl 代码背后只有一个 DependencyProperty:CurrentColor。
这样做:
- 将
Name="Root"
属性添加到 UserControl的xaml - 更改(Border 标签的)属性
背景="{绑定(bind) Path=CurrentColor}"
到:背景="{绑定(bind) 元素名称=根, Path=CurrentColor}"
- 删除有问题的 DataContext=this 来自 UserControl 的行 构造函数!
这应该就是它的全部。我写了一个证明上述内容的概念证明。如果你愿意,我可以发布它,但上面的代码应该是你所需要的。
关于c# - 为什么我不能将 viewmodel 属性绑定(bind)到自定义控件的依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2552675/