我有一个用户控件。使用XAML。它具有自己的属性,其ViewModel
对象设置为DataContext:
<ComboBox ItemsSource="{Binding Items}" SelectedIndex="0">
<ComboBox.DataContext>
<vm:WindowsProfilePicker />
</ComboBox.DataContext>
绑定到其DataContext值属性非常容易,并且可以按预期工作。
让我们说:
<Image Source="{Binding UserImage}" />
UserImage
是ViewModel
的属性。
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
Width
和Height
。我在做什么错了?
顺便说一句,很明显,我不希望该属性与ViewModel绑定,因为它是严格的表示功能,与数据无关。
必须在XAML(最好是样式)中设置视觉效果(如大小),在代码中设置数据(在我的情况下为用户个人资料图片),然后在控件的ViewModel中设置。
答案 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
});
(尽管AffectsRender
和AffectsMeasure
可能不是必需的)