如何在用户控件上添加可变图像

发布于 2024-12-22 06:32:14 字数 933 浏览 5 评论 0原文

我试图让用户控制从其包含元素传入图像的位置。目的是让我可以重用一组通用的视觉元素,而仅更改图像。例如:

控件用法:

<DataTemplate DataType={x:Type myType}>
    <local:MyControl PlotIconSource="..\Images\Scatter.png"/>
</DataTemplate>

控件内的图像

<UserControl x:Class="MyControl">
    <Image Source="{Binding PlotIconSource}"/>
</UserControl>

最后是 MyControl.xaml.cs 代码隐藏中的 PlotIconSource 的依赖属性。

    public ImageSource PlotIconSource
    {
        get { return (ImageSource)GetValue(PlotIconSourceProperty); }
        set { SetValue(PlotIconSourceProperty, value); }
    }

    public static readonly DependencyProperty PlotIconSourceProperty =
        DependencyProperty.Register(
            "PlotIconSource", 
            typeof(ImageSource), 
            typeof(PlotHeader), 
            new UIPropertyMetadata());

我确信我一路上错过了一些东西,所以任何帮助将不胜感激。

I'm trying to have a user control where an image is passed in from its containing element. The purpose is so that I can reuse a common set of visual elements while only changing the image. For example:

The control usage:

<DataTemplate DataType={x:Type myType}>
    <local:MyControl PlotIconSource="..\Images\Scatter.png"/>
</DataTemplate>

The Image inside the control

<UserControl x:Class="MyControl">
    <Image Source="{Binding PlotIconSource}"/>
</UserControl>

Finally the dependency property for PlotIconSource in the code-behind for MyControl.xaml.cs.

    public ImageSource PlotIconSource
    {
        get { return (ImageSource)GetValue(PlotIconSourceProperty); }
        set { SetValue(PlotIconSourceProperty, value); }
    }

    public static readonly DependencyProperty PlotIconSourceProperty =
        DependencyProperty.Register(
            "PlotIconSource", 
            typeof(ImageSource), 
            typeof(PlotHeader), 
            new UIPropertyMetadata());

I'm sure I've missed something along the way so any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月下伊人醉 2024-12-29 06:32:14

您可能希望通过 RelativeSource< 进行绑定/code>或使用 ElementName:(

<UserControl x:Class="MyControl" Name="control">
    <Image Source="{Binding PlotIconSource, ElementName=control}"/>
</UserControl>

不要设置 DataContext,它从外部是不可见的,并且会与用于继承的 的绑定混淆>数据上下文)

You might want to bind via RelativeSource or with ElementName:

<UserControl x:Class="MyControl" Name="control">
    <Image Source="{Binding PlotIconSource, ElementName=control}"/>
</UserControl>

(Do not set the DataContext, it will be invisible from the outside and mess with bindings meant for an inherited DataContext)

ζ澈沫 2024-12-29 06:32:14

我觉得不错,您是否收到错误消息或其他信息?

Looks right to me, are you getting an error message or something?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文