WPF按钮图像源绑定字符串依赖项属性

时间:2018-05-16 08:40:47

标签: c# wpf xaml

这在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完全相同,但使用Binding而不是x:bind。当我创建一个按钮并设置它的图像时。 。 。但是它没有显示alpha通道(我想这意味着我必须使用alpha蒙版并且有两个文件。)除此之外,将一堆东西从UWP移动到WPF XAML非常容易。

1 个答案:

答案 0 :(得分:3)

首先,您在{Binding prop_image}中使用了错误的属性路径,该路径应为{Binding prop_image_path}。由于此Binding在UserControl的XAML中属于其自己的属性之一,因此您还应将Binding的源对象指定为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 Casing,即

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); }
    }
}
相关问题