在wpf开发中,虽然可以通过XMAL编写炫酷的界面,但是有时候需要动态定义控件即:前台界面控件数量或者类型需要解析的数据或者其它条件确认再生成,这时候我们就需要通过后台cs中编写代码实现这一功能。
01
—
功能演示
02
—
功能说明
以上演示部分我们可以看到我前台的部分界面在窗体加载后并没有显示,而是选择文件解析后自动产生的,这种场景有时候也挺常用,特别是有大量同类型的数据显示到同类型的控件中时,我们就可以通过导入txt、Xml等文件的形式然后自动生成. 本地主要是举例演示实现这一功能,使用场景造得可能并不恰当,大家忍受下。
03
—
源码实现
前台代码:
<UserControl x:Class="Caliburn.Micro.Hello.DynamicalView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Caliburn.Micro.Hello"
xmlns:cal="http://www.caliburnproject.org" xmlns:dxlc="http://schemas.devexpress.com/winfx/2008/xaml/layoutcontrol"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1.5*" />
<RowDefinition Height="8.5*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" Grid.Row="0" Grid.ColumnSpan="2">
<TextBox Width="500" Height="30" Margin="3" Text="{Binding FilePath}" FontSize="14"
FontStyle="Normal" IsReadOnly="True" />
<Button Content="..." Margin="3" MinWidth="50"
cal:Message.Attach="[Event Click] = [Action SelectFile()]" />
</StackPanel>
<GroupBox Grid.Column="0" Grid.Row="1" Margin="3">
<GroupBox.Header>
<dxlc:LayoutItem Label="Student" Foreground ="Green" />
</GroupBox.Header>
<dxlc:LayoutControl>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="0"
cal:Message.Attach="[Event Loaded] = [Action StudentGridLoaded($source)]" />
</dxlc:LayoutControl>
</GroupBox>
<GroupBox Grid.Column="1" Grid.Row="1" Margin="3">
<GroupBox.Header>
<dxlc:LayoutItem Label="Teacher" Foreground ="Blue" />
</GroupBox.Header>
<dxlc:LayoutControl>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="0"
cal:Message.Attach="[Event Loaded] = [Action TeacherGridLoaded($source)]" />
</dxlc:LayoutControl>
</GroupBox>
</Grid>
</UserControl>
这里使用了Caliburn.Micro框架,所以需要引用名称空间
xmlns:cal="http:/