gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:34:09 26 4
gpt4 key购买 nike

假设要创建一个左侧有一个小椭圆的自定义按钮。我希望这个椭圆的颜色是数据可绑定(bind)的。

因此,我启动了 Blend,并在表面上放置了一个按钮,然后编辑模板的副本。我现在有了我的自定义模板,我在里面放了一个小的 Ellipse:

...

<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>

...

我右键单击此按钮并选择名为MyButtonMake into UserControl。在此按钮的代码中,我为 Brush` 添加了自定义 dependency 属性:



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")绑定(bind)到我的 MyColor 属性?

编辑:所以我使用 Fill={TemplateBinding MyColor} 在用户控件中绑定(bind)了 Fill 属性,但随后我得到了 Property MyColor was not found in type Button。好的,所以我需要将我的模板定位到自定义 MyButton 类型,但是我该怎么做呢?我可以简单地将 Button 更改为 MyButton,因为这样我就会得到 Property 'ContentTemplate' was not found in type 'MyButton'

<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 控件放置的默认样式。用您的模板替换该样式中的 Template。现在模板中的 Fill="{TemplateBinding MyColor}" 将起作用。

关于c# - 如何在自定义模板中使用自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7769728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com