Sco*_*son 2 c# wpf user-controls controls path
我必须开发一个wpf控件,它应该具有与众所周知的边界相同的行为.控制的形状应该是新的部分.每个可定义的封闭路径应用于定义控制的外观.
我需要帮助来实现这一目标.目前我不知道如何将矩形(??)与闭合路径互换.
任何帮助将受到高度赞赏.
编辑在这里直接回答你的问题.我们将编写一个ContentControl派生类,具有非常灵活的边框形式.这个想法的基础在于OpacityMask.
如果您想了解更多有关此方法的信息,请参阅Chris Cavanagh的圆角解决方案示例.
第1步.创建自定义控件FreeFormContentControl:
FreeFormContentControl.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfApplication5
{
public class FreeFormContentControl : ContentControl
{
public Geometry FormGeometry
{
get { return (Geometry)GetValue(FormGeometryProperty); }
set { SetValue(FormGeometryProperty, value); }
}
public static readonly DependencyProperty FormGeometryProperty =
DependencyProperty.Register("FormGeometry", typeof(Geometry), typeof(FreeFormContentControl), new UIPropertyMetadata(null));
static FreeFormContentControl()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(FreeFormContentControl),
new FrameworkPropertyMetadata(typeof(FreeFormContentControl))
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
主题\ Generic.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication5">
<Style TargetType="{x:Type local:FreeFormContentControl}">
<Setter Property="FormGeometry"
Value="M0,0 L1,0 1,1 0,1z" />
<Setter Property="Background"
Value="Black" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:FreeFormContentControl}">
<Grid>
<Path Name="mask"
Data="{TemplateBinding FormGeometry}"
Fill="{TemplateBinding Background}" />
<Grid>
<Grid.OpacityMask>
<VisualBrush Visual="{Binding ElementName=mask}" />
</Grid.OpacityMask>
<ContentPresenter />
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
有关自定义控件的更多信息,请参阅CodeProject.
第2步.用法.现在,您可以将任何内容放在此控件中.它的默认形状是矩形.因此,以下代码将导致常规的StackPanel UI:
<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cc="clr-namespace:WpfApplication5"
Title="Window1"
Height="300"
Width="300">
<Grid>
<cc:FreeFormContentControl>
<StackPanel>
<Button Content="Any" />
<Button Content="Content" />
<TextBlock Text="Goes" />
<TextBox Text="Here" />
</StackPanel>
</cc:FreeFormContentControl>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
但是,如果您定义自定义FormGeometry,您将获得自定义形状.例如,以下表单几何体在菱形内部显示内部控件:
<cc:FreeFormContentControl FormGeometry="M0,0.5 L0.5,0 1,0.5 0.5,1z">
Run Code Online (Sandbox Code Playgroud)
要从XAML中阅读有关几何定义的更多信息,请阅读MSDN上的相应部分:路径标记语法.
这里要提到的最后一件事是,您不必指定或计算FormGeomtry的具体像素值.网格使这个技巧成为可能.所以把它想象成百分比.即1 ==全宽或高.0.5 ==可用宽度/高度的一半,依此类推.
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
4331 次 |
| 最近记录: |