先上效果图:
思路:
1.从ChildWindow派生一个子类MyChildWindow
2.对MyChildWindow添加一个图片属性:Source
3.然后从用MyChildWindow创建一个TestChildWindow的XAML
4.重新定义样式,添加一个Image对象将Source和Image进行绑定
5.将定义的样式移植给MyChildWindow类
6.完工
1.从ChildWindow派生一个子类MyChildWindow
2.对MyChildWindow添加一个图片属性:Source
代码如下:
[csharp]
public class MyChildWindow:ChildWindow
{
public MyChildWindow()
{
} www.zzzyk.com
public static DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(ImageSource), typeof(MyChildWindow),null);
public ImageSource Source
{
get { return ((ImageSource)(base.GetValue(MyChildWindow.SourceProperty))); }
set { base.SetValue(MyChildWindow.SourceProperty, value); }
}
}
3.然后从用MyChildWindow创建一个TestChildWindow的XAML
XAML:
[html]
<controls:MyChildWindow x:Class="SilverlightApplication1.ChildWindow2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:SilverlightApplication1"
Width="400" Height="300"
Title="ChildWindow2" Source="/SilverlightApplication1;component/images/1.png">
<Grid x:Name="LayoutRoot" Margin="2">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button x:Name="CancelButton" Content="取消" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="1" />
<Button x:Name="OKButton" Content="确定" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,79,0" Grid.Row="1" />
</Grid>
</controls:MyChildWindow>
CS:
[csharp]
public partial class ChildWindow2 : MyChildWindow
{
public ChildWindow2()
{
InitializeComponent();
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
}
修改样式使用Blend进行修改:如下图
绑定图片Source
5.将定义的样式移植给MyChildWindow类
项目中创建Theme目录并创建Generic.xaml文件
将刚才的样式复制到Generic.xaml中更改一下TargetType="local:MyChildWindow"
更新一下MyChildWindow类的构造函数:
[csharp]
public MyChildWindow()
{
this.DefaultStyleKey = typeof(MyChildWindow);
}
6.以后使用就先创建一个ChildWindow将XAML和CS代码简单修改一下就可以了!