C# 在WPF C中动态创建表达式混合控件#
我在Expression Blend 4中创建了一个按钮。我想在运行时动态创建此按钮的实例 按钮的代码如下所示:C# 在WPF C中动态创建表达式混合控件#,c#,wpf,wpf-controls,expression-blend,C#,Wpf,Wpf Controls,Expression Blend,我在Expression Blend 4中创建了一个按钮。我想在运行时动态创建此按钮的实例 按钮的代码如下所示: <Button Content="Button" HorizontalAlignment="Left" Height="139" Margin="46,107,0,0" VerticalAlignment="Top" Width="412" Grid.ColumnSpan="2"> <Button.Background>
<Button Content="Button" HorizontalAlignment="Left" Height="139" Margin="46,107,0,0" VerticalAlignment="Top" Width="412" Grid.ColumnSpan="2">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
除了提供代码之外,你可以在解释你在做什么时添加注释,这样我就可以了解一般原则了
我知道这是一个简单的问题,所以我一直在阅读一些地方,如:,不幸的是,这些都没有帮助 在您的WPF应用程序中,您应该有一个
App.xaml
文件,在其中您可以添加样式
,这些样式将在您的UI之外使用
例如:
<Application x:Class="WpfApplication8.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!--The style for all your buttons, setting the background property to your custom brush-->
<Style TargetType="{x:Type Button}"> <!--Indicate that this style should be applied to Button type-->
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
要在按钮上使用此样式
,只需向按钮的样式
属性添加一个绑定即可
<Button Style="{StaticResource MyCustomStyle}" />
将xaml转换为代码非常容易,因为xaml使用完全相同的属性名称,就像我在上面发布的代码刷一样:
new LinearGradientBrush(Colors.Black, Colors.White, new Point(0.5, 1), new Point(0.5, 0))
是
Brush(firstColor,secondColor,StartPoint EndPoint)
Xaml只访问按钮中的属性,它们在C#中的名称都相同 看起来你想创建一个样式
。你能告诉我更多关于什么是样式的信息吗,在哪里可以学习样式。谢谢:-)@Brett WPF教程很棒:谢谢,这是一个很好的资源。不幸的是,这与我的目标并没有太大关系。我期待的是类似于Button NewButton=new Button()代码>。这都是XAML。我想我们一定是偏离了正轨。如果你使用第一个例子,我张贴每次你板条箱一个新的按钮,它将看起来像一个你在混合<代码>按钮新按钮=新按钮()带有App.xaml中样式的code>将看起来像你的blend oneadded code only示例,如果你真的想这样做,我真的很想编码它。你怎么知道密码是什么?特别是关于背景的部分是不直观的。有没有一个网站或其他资源,我可以查找来学习这些东西?你不想编码是什么意思?我知道代码是什么,因为你把代码贴在了你的问题上
new LinearGradientBrush(Colors.Black, Colors.White, new Point(0.5, 1), new Point(0.5, 0))
Brush(firstColor,secondColor,StartPoint EndPoint)