加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在自定义模板中使用自定义属性?

发布时间:2020-12-15 17:21:00 所属栏目:百科 来源:网络整理
导读:假设想要创建一个左侧有一个小椭圆的自定义按钮. 我希望这个椭圆的颜色是数据可绑定的. 所以我启动Blend并在表面上放置一个按钮并编辑模板的副本. 我现在拥有自定义模板,并在其中放入一个小椭圆: … Border x:Name="Background" BorderBrush="{TemplateBind
假设想要创建一个左侧有一个小椭圆的自定义按钮.
我希望这个椭圆的颜色是数据可绑定的.

所以我启动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.
在这个按钮后面的代码中,我为theBrush`添加了一个自定义依赖项属性:

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.
好的,所以我需要将我的模板定位到自定义MyButton类型,但我该怎么做呢?
我可以简单地将Button更改为MyButton,因为我在’MyButton’类型中找不到Property’ContentTemplate’

<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}”将起作用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读