简体   繁体   English

在xaml中设置属性控件

[英]Setting Properties a Control in xaml

I am creating a custom WPF control that uses an image inside of it. 我正在创建一个使用其中的图像的自定义WPF控件。 This custom control will be like any other, it will be declared in xaml. 这个自定义控件将像任何其他控件一样,它将在xaml中声明。 I want to have a public property for this control to specify the source of the internal image, much the same way you do this when using an Image control: 我想让这个控件有一个公共属性来指定内部图像的来源,就像使用Image控件时一样:

<Image Source="http://foo.com/bar.jpg"></Image>

What I want to do is have the following usage of my control: 我想要做的是使用我的控件:

<MyCustomControl ImageSource="http://foo.com/bar.jpg"></MyCustomControl>

And then internally, something like: 然后在内部,例如:

<UserControl class="MyCustomControl" ...>
     <Image Source="{Binding Imagesource}"></Image>
</UserControl>

What kind of setup do I need in my codebehind to get this to work? 我的代码隐藏中需要什么样的设置才能使其工作? i've tried a few things but can get nothing to work. 我已经尝试过一些东西但却无法工作。

What you need is a dependency property of type ImageSource and a proper binding, either use ElementName or RelativeSource , do not use the DataContext on UserControls . 你需要的是ImageSource类型的依赖属性和一个正确的绑定,使用ElementNameRelativeSource ,不要在UserControls上使用DataContext

<UserControl Name="control" x:Class="MyCustomControl" ...>
     <Image Source="{Binding ImageSource, ElementName=control}"/>
</UserControl>

<UserControl x:Class="MyCustomControl" ...>
     <Image Source="{Binding ImageSource,
                             RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</UserControl>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM