这在UWP中有效,但我无法使用WPF XAML显示图像。
我首先定义一个绑定图像文件路径的用户控件:
<Grid Height="70" Width="70">
<Border Style="{StaticResource border}">
<Button Style="{StaticResource button}">
<Image Source="{Binding prop_image}"/>
</Button>
</Border>
</Grid>
我将依赖属性定义为:
public static readonly DependencyProperty prop_image =
DependencyProperty.Register("prop_image_path", typeof(string),
typeof(user_control), null);
public string prop_image_path
{
get { return (string)GetValue(prop_image); }
set { SetValue(prop_image, value); }
}
然后,我尝试将其用作:
<local:user_control Grid.Column="1" Grid.Row="2"
prop_image_path="/Assets/my.png"/>
这与 UWP 完全相同,但使用绑定而不是 x:bind。 当我创建一个按钮并设置图像时,它可以工作......但它不显示 alpha 通道(我想这意味着我必须使用 alpha 掩码并有两个文件。 除此之外,将一堆东西从 UWP 移动到 WPF XAML 是轻而易举的。
首先,您在{Binding prop_image}
中使用了错误的属性路径,这应该是{Binding prop_image_path}
。由于此绑定位于用户控件的 XAML 中,到其自己的属性之一,因此还应将绑定的源对象指定为 UserControl 实例,如下所示:
<Image Source="{Binding prop_image_path,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
除此之外,WPF 依赖项属性系统还要求您遵循依赖项属性标识符字段的命名约定。
它必须像带有Property
后缀的属性一样命名:
public static readonly DependencyProperty prop_image_pathProperty =
DependencyProperty.Register(
"prop_image_path",
typeof(string),
typeof(user_control),
null);
您可能还会注意到您的命名方案有点不常见。根据广泛接受的约定,C#/.NET 类型和属性名称应使用 Pascal 大小写,即
public class MyUserControl
{
public static readonly DependencyProperty ImagePathProperty =
DependencyProperty.Register(
nameof(ImagePath),
typeof(string),
typeof(MyUserControl));
public string ImagePath
{
get { return (string)GetValue(ImagePathProperty); }
set { SetValue(ImagePathProperty, value); }
}
}