【问题标题】:WPF User Control - Round corners programmaticallyWPF 用户控件 - 以编程方式圆角
【发布时间】:2010-04-08 16:18:40
【问题描述】:

另一个 WPF 问题...

<UserControl x:Class="TKEApp.Components.UserControls.ButtonControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Background="Black">
        <TextBlock Foreground="White" Background="Brown" Name="lblCaption" TextAlignment="Center"></TextBlock>
    </Grid>
</UserControl>

在应用程序代码中的某个地方,我有一个此控件的实例,我需要以编程方式对其进行圆角处理。这可能吗?

【问题讨论】:

    标签: wpf user-controls shape


    【解决方案1】:
    <UserControl x:Class="TKEApp.Components.UserControls.ButtonControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Background="Transparent"> 
    <Border x:Name="border"  Background="Black" BorderThickness="5" BorderBrush="Yellow"  > 
        <TextBlock Foreground="White" Background="Brown" Name="lblCaption" TextAlignment="Center"></TextBlock> 
    </Border> 
    

    首先使用 FindName 方法找出用户控件,然后

        Border brd=usercontrol.FindName("border") as Border;brd.CornerRadius=new CornerRadius(5);
    

    【讨论】:

      【解决方案2】:

      您还可以使用 Rectangle 的 RadiusX 和 RadiusY 创建圆角。

      检查this,希望对您有所帮助!!

      【讨论】:

        【解决方案3】:
        <Button x:Name="bbb"> b </Button>
        

        var r=bbb.Template.FindName("border",bbb);
        ((Border)r).CornerRadius = new CornerRadius(40);
        

        在构造函数外部调用,可能在 Loaded 事件上。

        【讨论】:

        • 好的,效果很好。并且不需要显式的 XAML 边框元素。对我来说,这应该是评分最高的答案。
        【解决方案4】:

        您需要使用边框来提供圆角,因此您可以执行以下操作:

        <UserControl x:Class="TKEApp.Components.UserControls.ButtonControl"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
            <Border x:Name="border" Background="Black">
                <TextBlock Foreground="White" Background="Brown" Name="lblCaption" TextAlignment="Center"></TextBlock>
            </Border>
        </UserControl>
        

        然后给你的 UserControl 添加一个属性:

        public int BorderRadius
        {
            get { return border.CornerRadius; }
            set { border.CornerRadius = value; }
        }
        

        这允许您从代码中设置边框的 CornerRadius。

        【讨论】:

        • 我需要以编程方式进行,C# 代码,而不是 XAML,而且我想使用另一种解决方案,而不是用边框包围它。不过还是谢谢。
        • 抱歉,我没有注意到其中的编程部分。我认为除了使用边框之外没有任何方法可以制作圆角。不过我会问,为什么你要这样做?你只是想改变按钮控件的外观吗?如果是这样,有比使用 UserControl 重新创建按钮更好的方法。
        • 更新了答案,让您可以按照自己的要求去做。不过,您仍然需要边框。但我认为你应该在走这条路之前先看看 WPF 的主题功能。
        • 我需要为视觉设计师做这件事。此用户控件只是一个简单的控件,例如缘故。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-30
        • 1970-01-01
        相关资源
        最近更新 更多