首页 文章

为什么我不能将viewmodel属性绑定到自定义控件的依赖项属性

提问于
浏览
3

我想在我的wpf应用程序中使用颜色选择器,我在this codeproject页面上看到了一个漂亮的颜色选择器 . 控件正常工作,直到我想将控件连接到视图模型 . 我用这个viewmodel创建了一个小测试程序:

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>

在我的测试应用程序中的主窗口的加载事件中,我将viewmodel设置为datacontext,如下所示:

DataContext = new ColorViewModel();

问题是我似乎无法将viewmodel的LineColor属性绑定到ColorPickerControlView的CurrentColor属性 . ColorPickerControlView的CurrentControl属性似乎没问题 . 构造函数如下所示:

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

在UserControl的构造函数中,有一行this.DataContext = this;我读到绑定依赖项属性是必要的 . 我将viewmodel设置为datacontext时是否覆盖此行,这就是为什么我无法绑定到CurrentColor属性?有没有解决方法?还是我犯了另一个错误?

4 回答

  • 8

    您认为UserControl的构造函数中的 DataContext=this 短语是否会从绑定到外部视图模型中转发,这是正确的 . 它在this question中被讨论过 . 然而,这很容易解决 . 在UserControl的代码中只有一个DependencyProperty,xaml绑定到:CurrentColor .

    做这个:

    • Name="Root" 属性添加到UserControl的xaml的UserControl标记

    • 将(Border标签的)属性 Background="{Binding Path=CurrentColor}" 更改为:
      Background="{Binding ElementName=Root, Path=CurrentColor}"

    • 从UserControl的构造函数中删除有问题的DataContext = this行!

    这应该就是它的全部内容 . 我写了一个概念证明,证明了上述情况 . 如果你愿意,我可以发布它,但上面的代码应该是你所需要的 .

  • 0

    两个绑定都必须将属性的值与设置进行冲突 . 尝试设置 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 =这一行并不是真正需要的,因为你要用ViewModel的实例替换DataContext . 您也不需要在Loaded事件处理程序上分配DataContext . 只需在构造函数上设置它 . 您可以在调用InitializeComponent方法后设置它 .

  • 0
    • 在文件ColorPickerControlView.xaml.cs中删除行DataContext = this

    • 将ColorPickerControlView.xaml中的绑定更改为Background = "{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=}, Path=CurrentColor}"

相关问题