如何绑定到控件属性本身而不是DataContext值属性?

时间:2019-07-08 10:54:11

标签: c# .net wpf xaml

我有一个用户控件。使用XAML。它具有自己的属性,其ViewModel对象设置为DataContext:

<ComboBox ItemsSource="{Binding Items}" SelectedIndex="0">
  <ComboBox.DataContext>
    <vm:WindowsProfilePicker />
  </ComboBox.DataContext>

绑定到其DataContext值属性非常容易,并且可以按预期工作。

让我们说:

<Image Source="{Binding UserImage}" />

UserImageViewModel的属性。

Image元素是我的用户控件的一部分。控件具有自己的名为ImageSize的属性,定义如下:

public static readonly DependencyProperty ImageSizeProperty
  = DependencyProperty.Register(
    "ImageSize",
    typeof(double),
    typeof(WindowsProfilePicker),
    new FrameworkPropertyMetadata(126.0)
);

我们当然在代码中有getter和setter方法:

public double ImageSize {
  get => (double)GetValue(ImageSizeProperty);
  set => SetValue(ImageSizeProperty, value);
}

现在,我想在UserControl的XAML中引用该属性。看起来像这样:

<Image
  Width="
    {Binding RelativeSource={RelativeSource AncestorType=local:WindowsProfilePicker},
      Path=ImageSize}"
  Height="{Binding RelativeSource={RelativeSource AncestorType=local:WindowsProfilePicker},
      Path=ImageSize}"
  Source="{Binding UserImage}" />

好吗?并非如此,这是行不通的。我没有错误,没有警告,但是没有设置图像尺寸。控件中的图像根据源位图大小设置其大小。当我用数字替换绑定时,它可以工作,大小是固定的。但是,我希望将新控件的ImageSize属性用作Image WidthHeight。我在做什么错了?

顺便说一句,很明显,我不希望该属性与ViewModel绑定,因为它是严格的表示功能,与数据无关。

必须在XAML(最好是样式)中设置视觉效果(如大小),在代码中设置数据(在我的情况下为用户个人资料图片),然后在控件的ViewModel中设置。

1 个答案:

答案 0 :(得分:0)

尝试像这样配置属性元数据:

    public static readonly DependencyProperty ImageSizeProperty
      = DependencyProperty.Register(
        "ImageSize",
        typeof(double),
        typeof(WindowsProfilePicker),
        new FrameworkPropertyMetadata((double)126.0, 
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault
            | FrameworkPropertyMetadataOptions.AffectsRender
            | FrameworkPropertyMetadataOptions.AffectsMeasure)
    );

    [TypeConverter(typeof(LengthConverter))]
    public double ImageSize
    {
        get => (double)GetValue(ImageSizeProperty);
        set => SetValue(ImageSizeProperty, value);
    }

    public static readonly DependencyProperty ImageSizeProperty
      = DependencyProperty.Register(
        "ImageSize",
        typeof(double),
        typeof(WindowsProfilePicker),
        new FrameworkPropertyMetadata((double)126.0, 
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault
            | FrameworkPropertyMetadataOptions.AffectsRender
            | FrameworkPropertyMetadataOptions.AffectsMeasure)
    {
         BindsTwoWayByDefault = true,
         DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
     });

(尽管AffectsRenderAffectsMeasure可能不是必需的)

相关问题