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

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

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 text box and 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 main window of my test application, I set the viewmodel to the datacontext as follows:

 DataContext = new ColorViewModel();

, LineColor viewmodel CurrentColor ColorPickerControlView. CurrentControl ColorPickerControlView . :

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

UserControl this.DataContext = this; , . , CurrentColor? ? ?

+3
4

, , DataContext=this UserControl , viewmodel. . . UserControl DependencyProperty, xaml: CurrentColor.

:

  • Name="Root" UserControl UserControl xaml
  • ( Border) Background="{Binding Path=CurrentColor}" to:

    Background="{Binding ElementName=Root, Path=CurrentColor}"

  • DataContext = this UserControl !

, . , . , , , .

+8

. Mode=OneWay

<StackPanel Orientation="Horizontal">
    <TextBlock Text="Please Select a Color" FontWeight="Bold" Margin="10"
               Foreground="{Binding Path=LineColor, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"/>
     <vw:ColorPickerControlView x:Name="ForeColorPicker" Margin="10"
               CurrentColor="{Binding Path=LineColor, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay }"/>
</StackPanel>
0

this.DataContext = , DataContext ViewModel. DataContext Loaded. . InitializeComponent.

0
  • DataContext = this ColorPickerControlView.xaml.cs
  • ColorPickerControlView.xaml Background = "{Binding RelativeSource = {RelativeSource FindAncestor, AncestorType = {x: CustomWPFColorPicker: ColorPickerControlView}},               Path = CurrentColor}"
0

Source: https://habr.com/ru/post/1739294/


All Articles