【问题标题】:How to add variable Image on User Control如何在用户控件上添加可变图像
【发布时间】:2011-12-20 15:15:48
【问题描述】:

我正在尝试使用用户控件,其中图像是从其包含元素传入的。目的是让我可以重用一组通用的视觉元素,同时只更改图像。例如:

控件用法:

<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());

我确定我在此过程中遗漏了一些东西,因此我们将不胜感激。

【问题讨论】:

    标签: c# wpf xaml user-controls dependency-properties


    【解决方案1】:

    您可能希望通过RelativeSourceElementName 进行绑定:

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

    (不要设置DataContext,它会从外部不可见,并且会与用于继承的DataContext 的绑定混淆)

    【讨论】:

    • 我试过 无济于事;但是,使用 ElementName 方法有效。知道如何在没有 ElementName 的情况下做到这一点吗?
    • RelativeSource 与Source="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=PlotIconSource}" 合作,问题在于Self 指的是Image,而不是包含UserControl。感谢您为我指明正确的方向。
    • 不客气,很高兴它有帮助。好吧,当我说的相对来源正是我的意思时,我认为这很明显......
    【解决方案2】:

    在我看来是正确的,你收到错误消息还是什么?

    【讨论】:

    • 我收到“System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“ScatterPlotViewModel”(HashCode=40544074)上找不到“PlotIconSource”属性。BindingExpression:路径=PlotIconSource; DataItem='ScatterPlotViewModel' (HashCode=40544074); 目标元素是'Image' (Name=''); 目标属性是'Source' (类型'ImageSource')"
    • 啊,当然……数据上下文/绑定是缺少的元素
    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多