Silverlight:为什么可以';设计器看不到依赖项属性吗?
我必须创建具有公共属性的Silverlight用户控件,这些属性应该在内部控件中使用Silverlight:为什么可以';设计器看不到依赖项属性吗?,silverlight,dependency-properties,Silverlight,Dependency Properties,我必须创建具有公共属性的Silverlight用户控件,这些属性应该在内部控件中使用 public partial class MyControl : UserControl { public static readonly DependencyProperty MyCustomProperty = DependencyProperty.Register( "MyCustom", typeof(string), typeof(MyControl)
public partial class MyControl : UserControl
{
public static readonly DependencyProperty MyCustomProperty =
DependencyProperty.Register(
"MyCustom", typeof(string), typeof(MyControl),
new PropertyMetadata("defaultValue"));
public string MyCustom
{
...
}
我尝试了几种绑定方法,但由于某种原因,没有看到所有的fail-dependency属性。
例如,此直接绑定失败:
<UserControl x:Class="...MyControl"
...
x:Name="mc"
>
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Image Source="{Binding Path=MyCustom, Mode=OneWay, ElementName=mc}" />
</Grid>
</UserControl>
我做错了什么 你所做的不是一个好的模式。UserControl并不真正“拥有”name属性。如果另一个用户控件或页面将您的
MyControl
的实例放在其Xaml中,则它可以给它命名而不是“mc”,此时您的代码被破坏
相反,请使用以下方法:-
<UserControl x:Class="...MyControl"
>
<Grid x:Name="LayoutRoot" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Image Source="{Binding Path=Parent.MyCustom, Mode=OneWay, ElementName=LayoutRoot}" />
</Grid>
</UserControl>
现在,在另一个用户控件或承载
MyControl
的页面中,您可以使用字符串分配此MyCustom
属性。但是,在代码中,您需要创建一个类似于BitmapImage
的实例来分配给此属性。Silverlight 4解决了命名问题。看这个。另外,图像的父级不是控制网格吗?@Code裸体:很好,这个命名问题似乎确实在SL4中排序。我仍然认为在用户控件上指定一个名称不是一个好主意,但是还有多少其他控件的名称有“默认”值。对于父控件
,它没有引用图像控件的父控件,ElementName指向LayoutRoot。因此,Parent
指向LayoutRoot的父级,即用户控件。啊,遗漏了ElementName部分:-)您在输出窗口中看到绑定错误了吗?很可能您的字符串需要转换为Anthony提到的ImageSource。
public partial class MyControl : UserControl
{
public static readonly DependencyProperty MyCustomProperty =
DependencyProperty.Register(
"MyCustom", typeof(ImageSource), typeof(MyControl),
new PropertyMetadata(null));
[TypeConverter(typeof(ImageSourceConverter))]
public ImageSource MyCustom
{
...
}