首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >WPF按钮图像源绑定字符串依赖项属性

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

Stack Overflow用户
提问于 2018-05-16 08:40:47
回答 1查看 601关注 0票数 1

这在UWP中有效,但我无法获得使用WPF XAML显示的图像。

首先定义一个UserControl,它绑定图像文件的路径:

代码语言:javascript
运行
复制
<Grid Height="70" Width="70">
    <Border Style="{StaticResource border}">
        <Button Style="{StaticResource button}">
            <Image Source="{Binding prop_image}"/>
        </Button>
    </Border>
</Grid>

我将依赖项属性定义为:

代码语言:javascript
运行
复制
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); }
}

然后,我尝试将其消费为:

代码语言:javascript
运行
复制
<local:user_control Grid.Column="1" Grid.Row="2"
    prop_image_path="/Assets/my.png"/>

它与UWP完全相同,但是绑定而不是x:bind。当我创建一个按钮并设置图像时,它可以工作。。。但是它没有显示alpha通道(我猜这意味着我必须使用alpha掩码并有两个文件)。除此之外,把一堆东西从UWP转移到WPF XAML是件很简单的事情。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-16 08:50:57

首先,您在{Binding prop_image}中使用了错误的属性路径,应该是{Binding prop_image_path}。由于此绑定位于UserControl的XAML中,因此应该将绑定的源对象指定为UserControl实例,如下所示:

代码语言:javascript
运行
复制
<Image Source="{Binding prop_image_path,
                RelativeSource={RelativeSource AncestorType=UserControl}}"/>

此外,WPF依赖项属性系统要求您遵守依赖属性标识符字段的命名约定。

必须将其命名为具有Property后缀的属性:

代码语言:javascript
运行
复制
public static readonly DependencyProperty prop_image_pathProperty =
    DependencyProperty.Register(
        "prop_image_path",
         typeof(string),
         typeof(user_control),
         null);

您可能还会注意到,您的命名方案有点不常见。根据广泛接受的惯例,C#/.NET类型和属性名称应使用Pascal大小写,即

代码语言:javascript
运行
复制
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); }
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50366139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档