c# – 如何在自定义模板中使用自定义属性?
假设想要创建一个左侧有一个小椭圆的自定义按钮.
我希望这个椭圆的颜色是数据可绑定的. 所以我启动Blend并在表面上放置一个按钮并编辑模板的副本. … <Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="White" CornerRadius="3"> <Grid Background="{TemplateBinding Background}" Margin="1"> <snip /> <!-- My ellipse here --> <Ellipse x:Name="ellipse" Width="10" Height="10" HorizontalAlignment="Left" /> </Grid> </Border> … 我右键单击此按钮并选择Make into UserControl,命名为MyButton. public Brush MyColor { get { return (Brush)GetValue(MyColorProperty); } set { SetValue(MyColorProperty,value); } } public static readonly DependencyProperty MyColorProperty = DependencyProperty.Register("MyColor",typeof(Brush),typeof(MyButton),new PropertyMetadata(new opertyChangedCallback(MyColorPropertyChanged))); private static void MyColorPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) { var thisControl = d as MyButton; } 然后我可以使用我的自定义按钮: <local:MyButton Width="130" MyColor="Red"/> 但后来我被卡住了.如何将我的椭圆颜色(上面的x:Name =“ellipse”)绑定到MyColor属性? 编辑:所以我使用Fill = {TemplateBinding MyColor}绑定用户控件中的Fill属性,但后来我在类型Button中找不到属性MyColor. <UserControl <snip/> x:Class="SilverlightApplication1.MyButton"> <UserControl.Resources> <Style x:Key="ButtonStyle1" TargetType="Button"> <snip/> </Style> </UserControl.Resources> <Grid x:Name="LayoutRoot"> <Button Content="Test Button" Style="{StaticResource ButtonStyle1}"/> </Grid> </UserControl> 解决方法
这里的问题是UserControl不是您控制的正确基础.你应该创建一个模板控件.
在Visual Studio中,将新的“Silverlight模板化控件”添加到名为MyButton的项目中. 打开MyButton.cs并将其基类更改为Button.将MyColor依赖项属性放入代码中. 打开Themes / Generic.xaml并找到为此新MyButton控件放置的默认样式.用模板替换该样式中的模板.现在,模板中的Fill =“{TemplateBinding MyColor}”将起作用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |