2014-03-30 115 views
0

我得到了一个userControl,并且我想从包含userControl的页面设置图像按钮。在UserControl按钮中设置图像源

如果我以这种方式在usercontrol中设置我的按钮图像,它的工作原理,但我不能改变。

<Button blablabla> 
    <Image Source="../../../Assets/truck-512.png"/> 
</Button> 

所以我从代码隐藏

public ImageSource ButtonSource 
    { 
     get { return (ImageSource)GetValue(SourceProperty); } 
     set { SetValue(SourceProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Source. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty SourceProperty = 
     DependencyProperty.Register("Source", typeof(ImageSource), typeof(TruckFormUC),null); 

,并在我的userContol XAML设置我的形象定义属性如下

<Image x:Name="imgIcon" Source="{Binding Path=ButtonSource}"/> 

比我用我的用户在我的网页和我尝试设置图像源,但它不起作用

<UC:TruckFormUC x:Name="truckForm" 
ButtonSource="../../../Assets/truck-512.png"/> 

非常感谢


用户控件和页面都在同一个文件夹中。

+0

您不应该需要依赖项属性。只有inotiftypropertychanged被更改。这可能有所帮助:http://stackoverflow.com/questions/19021149/windows-phone-8-image-binding – WiredPrairie

+0

我的用户控件不仅在一个按钮,我怎么能从其他页面设置ButtonSource属性?我不能使用 ArghArgh

+0

UserControls可以接受来自当前数据上下文的绑定。它不需要“通过”。 – WiredPrairie

回答

0

您的绑定正在寻找DataContext对象上的ButtonSource属性。如果你想绑定到你的UserControl,你应该使用相对绑定。

<Image x:Name="imgIcon" Source="{Binding 
RelativeSource={RelativeSource FindAncestor, AncestorType=UC:TruckFormUC}, 
Path=ButtonSource}"/> 

RelativeSource标记扩展MSDN文章了解更多信息

0

你也应该能够使用元素结合。

<Image x:Name="imgIcon" Source="{Binding ElementName=truckForm, Path=ButtonSource}"/>