Why can't I Bind a viewmodel property to a dependency property of a custom control

Posted by Robert on Stack Overflow See other posts from Stack Overflow or by Robert
Published on 2010-03-31T12:03:44Z Indexed on 2010/03/31 14:43 UTC
Read the original article Hit count: 371

I want to use a color picker in my wpf application and I saw a nice looking one on this codeproject page. The control works fine until I want to connect the control to a viewmodel. I created a small test program with this viewmodel:

public class ColorViewModel : ViewModelBase
{
    public ColorViewModel()
    {
        LineColor = Brushes.Yellow;
    }

    SolidColorBrush _brushColor;
    public SolidColorBrush LineColor
    {
        get { return _brushColor; }
        set
        {
            _brushColor = value;
            RaisePropertyChanged(() => LineColor);
        }
    }
}

The test program has a textbox and the colorpicker controls:

<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>

In the loaded event of the window I set the viewmodel to the datacontext like this:

 DataContext = new ColorViewModel();

The problem is that I can't seem to bind the LineColor property of the viewmodel to the CurrentColor property of the ColorPickerControlView. The CurrentControl property of the ColorPickerControlView seems to be fine. The constructor looks like this:

public ColorPickerControlView()
{
    this.DataContext = this;
    InitializeComponent();
    CommandBindings.Add(new CommandBinding(SelectColorCommand, SelectColorCommandExecute));
}

In the constructor of the UserControl there is the line this.DataContext = this; I read that is is necessary to bind the dependency properties. Do I override this line when I set my viewmodel to the datacontext and is that why I can't bind to the CurrentColor property? Is there any workaround? Or did I make another mistake?

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf