您的位置:首页 > Web前端 > CSS

Wpf 动态添加控件设置样式

2013-05-17 09:51 971 查看
新公司主要用wpf做项目,之前也没有接触过这类东西,经过一周的学习发现wpf的页面布局,样式设置和网页设计差不多。
两者都有样式文件可以为控件统一设置样式,就连优先级都差不多,发现还挺有意思。下面进入正题,怎样在程序运行后动态添加控件。

  要想添加控件,容器是必须要有的,几大布局控件都可以 Grid Canvas UniformGrid DockPanel StackPanel WrapPanel 下面就以WrapPanel 为例进行演示

先上代码

/// <summary>

/// 添加控件的方法

/// </summary>

/// <param name="Container"> Pannel类的实例</param>

/// <param name="Control">UIElement 实例</param>

public static void DynamicAdd(Panel Container, UIElement Control)

{

Container.Children.Add(Control);

}

private void buttonAdd_Click(object sender, RoutedEventArgs e)

{

Button btn = new Button();

btn.Width = 200;

btn.Height = 70;

//设置按钮样式使用此种方法必须将资源文件引用到当前页面

btn.Style = Resources["NoticeButton"] as Style;

//此种方法也可以设置样式

//获取App.xaml中的样式个人更喜欢这种

//Style style = (Style)this.FindResource("NoticeButton");

//为按钮设置样式

// btn.Style = style;

//将btn添加到ufg

DynamicAdd(wrp, btn);

}


这里是后台的代码很简单只是在设置样式的时候要注意一下用哪种方法

前台xaml代码主要是对资源的引用

<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary  Source="/Css/EventsButton.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition ></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
</Grid.RowDefinitions>
<WrapPanel Name="wrp" Grid.Row="0"></WrapPanel>
<Button Content="添加" Grid.Row="1" Height="23" HorizontalAlignment="Center"  Name="buttonAdd" VerticalAlignment="Top" Width="75" Click="buttonAdd_Click" />
</Grid>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: