这在UWP中有效,但我无法获得使用WPF XAML显示的图像。
首先定义一个UserControl,它绑定图像文件的路径:
<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是件很简单的事情。
发布于 2018-05-16 08:50:57
首先,您在{Binding prop_image}中使用了错误的属性路径,应该是{Binding prop_image_path}。由于此绑定位于UserControl的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); }
}
}https://stackoverflow.com/questions/50366139
复制相似问题