![](/img/trans.png)
[英]UserControl in WinUI 3: how to set the 'source' property of an image and the 'click' event of a button?
[英]Setting Image Source in a UserControl Button
我有一个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}"/>
比我在页面中使用我的userControl尝试设置图像源,但是它不起作用
<UC:TruckFormUC x:Name="truckForm"
ButtonSource="../../../Assets/truck-512.png"/>
非常感谢
userControl和页面位于同一文件夹中。
您的绑定正在寻找DataContext对象上的ButtonSource属性。 如果要绑定到UserControl,则应使用相对绑定。
<Image x:Name="imgIcon" Source="{Binding
RelativeSource={RelativeSource FindAncestor, AncestorType=UC:TruckFormUC},
Path=ButtonSource}"/>
有关更多信息,请参见RelativeSource标记扩展MSDN文章。
您还应该能够使用元素绑定。
<Image x:Name="imgIcon" Source="{Binding ElementName=truckForm, Path=ButtonSource}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.