先上效果圖:
思路:
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.2cto.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代碼簡單修改一下就可以了!