mikeo_410


Tips XAML

  1. レイアウト
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="320"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="40"></RowDefinition>
        <RowDefinition Height="120"></RowDefinition>
        <RowDefinition Height="80"></RowDefinition>
    </Grid.RowDefinitions>
     
  2. TextBlock
    <TextBlock Grid.Row="2" TextWrapping="Wrap" FontSize="14" Background="MintCream">
        Linux-Apacheの...<LineBreak/>「butunn1」...
    </TextBlock>
  3. StackPanel、DockPanel
    Canvas は、コントロールの位置指定が必要だが、StackPanel、DockPanelは、Orinetationで指定した方向に順次配置する。
  4. StackPanel と DockPanel の差異
    よく分からない。
  5. プロジェクトの追加で、Silverlightアプリケーションで、「Silverlightをホストするための新しいASP.NET Web プロジェクトを追加する」を選ぶと「プロジェクト名」と「プロジェクト名.Web」の2つのプロジェクトができる。
  6. このとき、「ソリュ-ションエクスプローラ」でサブフォルダを作り、「Silverlightユーザコントロール」を追加したら、表示されない。コンパイルなどではエラーにならない。
  7. XAMLに書かれたイベントハンドラが、ビハンドコードにあるかどうかは使われるまでチェックされない。 チャックされることもある。
  8. 「Silverlightユーザコントロール」を追加したら、引用する側では
    <UserControl x:Class="sla1.Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:uc="clr-namespace:SilverlightLibrary"

        Width="360" Height="360">
    の、ように名前空間を設定し、
    <uc:SimpleSlider Text="外側の円の回転" ... />
    の、ように使う。
  9. 「Silverlightクラスライブラリ」を作って,「Silverlightユーザコントロール」を入れた場合(「Silverlightユーザコントロール」をDLLにした場合)は、ツールボックスの下の余白で、右ボタンメニューから「アイテムの選択」で、「Silverlightコンポーネント」としてDLLを追加する。
  10. Silverlightでは、TextBlockにbackgroundが記述できなかった。StackPlainの中に入れて、StackPlainにbackgroundを記述した。
  11. 枠を描くには、 
    <Border BorderBrush="Blue" BorderThickness="1"> ... </Border>
  12. 「新しいプロジェクト」で自動的に作られる .xaml について
    .xaml.cs と対で作られる。
    アプリケーション・クラスとスタート・クラスを定義する。
    app.xaml の Application タグのStartupUriでwindow1.xaml、page1.xamlの使用が定義される。ただし、Silverlightの場合は別で、良く分からない。  
  13. .xaml と .xaml.cs の対で作られるが、.cs が不要なら、.xaml のApplicationやWindowなどのタグから、x:Class= ... を削除すれば、.cs は参照されない。
  14. XY平面を数学のように。Y軸を反転。原点を中央に。
    1. <Window x:Class="wpf_color_map1.Window1"
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4.     Title="Hue" Height="300" Width="300">
    5.     <Grid>
    6.         <Canvas x:Name="canvas1" Loaded="canvas1_Loaded">
    7.             <Canvas.RenderTransform>
    8.                 <MatrixTransform>
    9.                     <MatrixTransform.Matrix>
    10.                         <Matrix M11="1" M12="0" M21="0" M22="-1" OffsetX="150" OffsetY="150"></Matrix>
    11.                     </MatrixTransform.Matrix>
    12.                 </MatrixTransform>
    13.             </Canvas.RenderTransform>
    14.             <Line X1="-100" Y1="0" X2="100" Y2="0" Stroke="Green" StrokeThickness="1"/>
    15.             <Line X1="0" Y1="-100" X2="0" Y2="100" Stroke="Green" StrokeThickness="1"/>
    16.         </Canvas>
    17.     </Grid>
    18. </Window>
  15. Blenderからジオメトリを取り込む
    プラグイン(xaml_export.py)を使って、BlenderからXAML形式でエクスポートする。
    この出力ファイルを編集して使う。
    <GeometryModel3D> エレメント1つを残して、それ以外を削除する。
    これを <ResourceDictionary> の要素にする。
    1. <ResourceDictionary
    2.   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    3.   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    4.     <MeshGeometry3D x:Key="_sphere"
    5.          Positions="-0.000001 -0.000001 -1.0 0.096133 0.019122 ..."
    6.      />
    7. </ResourceDictionary>

    使い方は、次の例参照。
  16. スペキュラ、発光
    Blenderで、球を描いて、XAMLでエクスポートし、ジオメトリだけを流用した。
    表面を塗るブラシの他に <EmissiveMaterial>、<SpecularMaterial> で、それぞれブラシを指定する。このとき指定する色は、色ではなく、表面を塗るブラシの色に対して演算(加算)する値だろうと思う。
    <SpecularMaterial> には、SpecularPower があり、ハイライト領域の先鋭さを制御できる。
    http://hp.vector.co.jp/authors/VA039696/xaml/sphere/iframe_sphere2.xaml
    (軸はビハインドコードで描いているので、XAMLだけのサンプルでは表示されない。)
    1. <Page ShowsNavigationUI="False"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    4. <!--リソース-->
    5. <Page.Resources>
    6. <ResourceDictionary>
    7. <ResourceDictionary.MergedDictionaries>
    8. <!--ジオメトリを別のXAMLファイルから読み込む-->
    9. <ResourceDictionary Source="sphere.xaml"/>
    10. </ResourceDictionary.MergedDictionaries>
    11. </ResourceDictionary>
    12. </Page.Resources>
    13. <Grid>
    14. <Grid.RowDefinitions>
    15. <RowDefinition/>
    16. <RowDefinition Height="54"/>
    17. </Grid.RowDefinitions>
    18. <Viewport3D x:Name="viewport1" Grid.Row="0">
    19. <Viewport3D.Camera>
    20. <!--カメラ-->
    21. <PerspectiveCamera
    22. LookDirection="-1, -1, -1" Position="2,2,2" FieldOfView="45">
    23. </PerspectiveCamera>
    24. </Viewport3D.Camera>
    25. <ModelVisual3D>
    26. <ModelVisual3D.Content>
    27. <!--ライト-->
    28. <DirectionalLight Color="White" Direction="1,-1,-1" />
    29. </ModelVisual3D.Content>
    30. </ModelVisual3D>
    31. <ModelVisual3D>
    32. <ModelVisual3D.Content>
    33. <!--リソースで定義したジオメトリを使用-->
    34. <GeometryModel3D Geometry="{StaticResource _sphere}">
    35. <GeometryModel3D.Material>
    36. <MaterialGroup>
    37. <!--物体の色-->
    38. <DiffuseMaterial Brush="Yellow"/>
    39. <!--物体の発光-->
    40. <EmissiveMaterial Brush="Gray"/>
    41. <!--ハイライト-->
    42. <SpecularMaterial Brush="White" SpecularPower="{Binding ElementName=slider1, Path=Value}"/>
    43. </MaterialGroup>
    44. </GeometryModel3D.Material>
    45. </GeometryModel3D>
    46. </ModelVisual3D.Content>
    47. </ModelVisual3D>
    48. </Viewport3D>
    49. <Grid Grid.Row="1">
    50. <StackPanel>
    51. <StackPanel Orientation="Horizontal">
    52. <TextBlock Text="SpecularPower :"/>
    53. <TextBlock Text="{Binding ElementName=slider1, Path=Value}"/>
    54. </StackPanel>
    55. <Slider Name="slider1" Minimum="2" Maximum="100" Value="10" Ticks="0.1"/>
    56. </StackPanel>
    57. </Grid>
    58. </Grid>
    59. </Page>
  17. XAMLを直接ブラウザ(IE)で開く
    <Window>ではなく、<Page>にする。
    x:Class=... は、削除。
    x:Name="..." の箇所は、単にName="..."として良いよう。
  18. 3Dの物体がテーブルに写る
     
    1. <Page
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4.     Background="Thistle">
    5.     <!--リソース-->
    6.     <Page.Resources>
    7.         <ResourceDictionary>
    8.             <ResourceDictionary.MergedDictionaries>
    9.                 <!--ジオメトリを別のXAMLファイルから読み込む-->
    10.                 <ResourceDictionary Source="sphere.xaml"/>
    11.             </ResourceDictionary.MergedDictionaries>
    12.         </ResourceDictionary>
    13.     </Page.Resources>
    14.     <!--表示領域-->
    15.     <StackPanel Margin="20">
    16.         <!--上段画像-->
    17.         <Border Name="original1" Width="200" Height="150">
    18.             <Border.Background>
    19.                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
    20.                     <GradientStop Offset="0.0" Color="Red" />
    21.                     <GradientStop Offset="1.0" Color="White" />
    22.                 </LinearGradientBrush>
    23.             </Border.Background>
    24.             <Viewport3D>
    25.                 <!--カメラ-->
    26.                 <Viewport3D.Camera>
    27.                     <PerspectiveCamera Position="3 2 4" LookDirection="-3 -1.35 -4"/>
    28.                 </Viewport3D.Camera>
    29.                 <!--照明-->
    30.                 <ModelVisual3D>
    31.                     <ModelVisual3D.Content>
    32.                         <DirectionalLight Direction="0 -5 -8"/>
    33.                     </ModelVisual3D.Content>
    34.                 </ModelVisual3D>
    35.                 <!--図形 球-->
    36.                 <ModelVisual3D>
    37.                     <ModelVisual3D.Content>
    38.                         <!--リソースで定義したジオメトリを使用-->
    39.                         <GeometryModel3D Geometry="{StaticResource _sphere}">
    40.                             <GeometryModel3D.Material>
    41.                                 <MaterialGroup>
    42.                                     <!--物体の色-->
    43.                                     <DiffuseMaterial Brush="Yellow"/>
    44.                                     <!--ハイライト-->
    45.                                     <SpecularMaterial Brush="White" SpecularPower="50"/>
    46.                                 </MaterialGroup>
    47.                             </GeometryModel3D.Material>
    48.                         </GeometryModel3D>
    49.                     </ModelVisual3D.Content>
    50.                 </ModelVisual3D>
    51.             </Viewport3D>
    52.         </Border>
    53.         <!--下段画像-->
    54.         <Rectangle Width="{Binding Path=ActualWidth, ElementName=original1}" 
    55.                Height="{Binding Path=ActualHeight, ElementName=original1}">
    56.             <Rectangle.Fill>
    57.                 <VisualBrush Opacity="0.5" Visual="{Binding ElementName=original1}">
    58.                     <VisualBrush.RelativeTransform>
    59.                         <MatrixTransform Matrix="1,0, 0,-1, 0,1">
    60.                         </MatrixTransform>
    61.                     </VisualBrush.RelativeTransform>
    62.                 </VisualBrush>
    63.             </Rectangle.Fill>
    64.         </Rectangle>
    65.     </StackPanel>
    66. </Page>


     
  19. スタイル
     
    1. <Page
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4.     Title="Page1">
    5.     <Page.Resources>
    6.         <!--スタイルがしてされていないTextBlockに作用する-->
    7.         <Style TargetType="TextBlock">
    8.             <Setter Property="Background" Value="Green"/>
    9.             <Setter Property="Foreground" Value="Yellow"/>
    10.         </Style>
    11.         <!--スタイルをキーで指定する場合-->
    12.         <Style x:Key="BG_RED" TargetType="TextBlock">
    13.             <Setter Property="Background" Value="OrangeRed"/>
    14.         </Style>
    15.         <!--スタイルのベースを継承して設定-->
    16.         <Style x:Key="BASED_ON" BasedOn="{StaticResource {x:Type TextBlock}}" TargetType="TextBlock">
    17.             <Setter Property="Background" Value="OrangeRed"/>
    18.         </Style>
    19.     </Page.Resources>
    20.     <Grid>
    21.         <StackPanel>
    22.             <TextBlock>
    23.             スタイルの設定でデフォルトの背景が緑になる。(文字の色は赤を指定)
    24.             </TextBlock>
    25.             <TextBlock Style="{StaticResource BG_RED}">
    26.                 背景が赤のスタイルをした。(文字色指定なし-絶対的なデフォルト)
    27.             </TextBlock>
    28.             <TextBlock Style="{StaticResource BASED_ON}">
    29.                 背景が赤のスタイルをした。(文字色指定なし-BasedOnによる)
    30.             </TextBlock>
    31.         </StackPanel>
    32.     </Grid>
    33. </Page>

  20. <Page.Resources>内に、x:Key="キー" で割り当てたオブジェクトにアクセスする。
    <XmlDataProvider x:Key="xmlDataProvider1" ...
    ビハインドコードで以下のように参照する。
    XmlDataProvider xdp = (XmlDataProvider)this.Resources.FindName("xmlDataProvider1");
    ※Resources["xmlDataProvider1"]で良い。(FindName()がない。)
  21. XAML中にURLを記述する場合、パラメータの分離用の & は、&amp; にエスケープする必要がある。(C#では不要)
  22. TextBoxで入力した文字列をURLのパラメータに使うには、ビハインドコードで、
    System.Web.HttpUtility.UrlEncode()
    を、使う。
  23. XmlDataProviderを使う場合、リソースにする以外に、<Grid>の中に書くこともできる。
    ルートの<Grid>に続いて、
    1. <Grid x:Name="grid1" Margin="8" Background="Tan">
    2.     <Grid.DataContext>
    3.         <XmlDataProvider x:Name="xmlDataProvider1" .../>
    4.     </Grid.DataContext>

    ビハインドコードで、Nameの名前が使える。
  24. ビハインドコードでバインドする。
    1. XmlDataProvider xdp = new XmlDataProvider();
    2. xdp.Source = new Uri("http://www...");
    3. xdp.XPath = "element/item";
    4. Binding bind=new Binding();
    5. bind.Source = xdp;
    6. grid1.SetBinding(Grid.DataContextProperty,bind);
  25. DataTemplate

      左図の左側は、ListBox。
      矩形の1つ1つが商品に対応していて商品の選択に使う。
    1. <!--ListBox-->
    2. <ListBox Grid.Row="1" ItemsSource="{Binding}" 
    3.          ItemTemplate="{DynamicResource ListItemTemplate}"
    4.          IsSynchronizedWithCurrentItem="True" />
      個々の矩形には、写真とメーカー、品名などから構成さる。
      この構成を定義しているのが、DataTemplate。 リソースとして定義している。内容には表示のレイアウトとバインディングが設定されている。

    1. <!--ListBox部分のテンプレート-->
    2. <Page.Resources>
    3.     <DataTemplate x:Key="ListItemTemplate">
    4.         <Border Margin="2" Height="100"
    5.                 BorderBrush="Blue" BorderThickness="1" CornerRadius="3">
    6.             <Grid>
    7.                 <Grid.ColumnDefinitions>
    8.                     <ColumnDefinition Width="100" />
    9.                     <ColumnDefinition Width="50" />
    10.                     <ColumnDefinition Width="180" />
    11.                 </Grid.ColumnDefinitions>
    12.                 <!--写真-->
    13.                 <Border Grid.Column="0" Margin="2" Background="LightYellow" 
    14.                             BorderBrush="Blue" BorderThickness="1" CornerRadius="3">
    15.                     <Image Margin="2,2,2,2" Source="{Binding XPath=image}" 
    16.                            Stretch="Uniform"/> 
    17.                 </Border>
    18.                 <!--項目名-->
    19.                 <StackPanel Grid.Column="1">
    20.                     <TextBlock Height="20">メーカー:</TextBlock>
    21.                     <TextBlock Height="40">品名:</TextBlock>
    22.                     <TextBlock Height="20">区分:</TextBlock>
    23.                     <TextBlock Height="20">タイプ:</TextBlock>
    24.                 </StackPanel>
    25.                 <!--項目値-->
    26.                 <StackPanel Grid.Column="2">
    27.                     <TextBlock Height="20" Text="{Binding XPath=maker}"/>
    28.                     <TextBlock Height="40" Text="{Binding XPath=name}"
    29.                                TextWrapping="Wrap" FontSize="16" 
    30.                                Foreground="DarkRed" />
    31.                     <TextBlock Height="20" Text="{Binding XPath=tag}"/>
    32.                     <TextBlock Height="20" Text="{Binding XPath=type}"/>
    33.                 </StackPanel>
    34.             </Grid>
    35.         </Border>
    36.     </DataTemplate>
    37. </Page.Resources>
  26. 丸いボタン(ControlTemplate)
    コントロールには、Templete プロパティがある。
      このプロパティにセットすることで、形状や色を変えられる。
    1. <Page
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    4.     <!--リソース-->
    5.     <Page.Resources>
    6.         <ControlTemplate x:Key="EllipseButton" TargetType="Button">
    7.             <Grid>
    8.                 <Ellipse Fill="Red"/>
    9.                 <Ellipse Margin="8" Fill="Green"/>
    10.                 <ContentPresenter HorizontalAlignment="Center"
    11.                                   VerticalAlignment="Center"/>
    12.             </Grid>
    13.         </ControlTemplate>
    14.     </Page.Resources>
    15.     <StackPanel>
    16.         <Button Width="100" Height="100" Template="{StaticResource EllipseButton}">
    17.         ボタン
    18.         </Button>
    19.     </StackPanel>
    20. </Page>

    変更内容は、ControlTemplate で設定する。 
     
  27.  丸いボタン(ControlTemplateを別ファイルで) 
    定義:
    1. <ResourceDictionary
    2.   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3.   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    4.     <ControlTemplate x:Key="EllipseButton" TargetType="Button">
    5.         <Grid>
    6.             <Ellipse Fill="Red"/>
    7.             <Ellipse Margin="8" Fill="Green"/>
    8.             <ContentPresenter HorizontalAlignment="Center"
    9.                               VerticalAlignment="Center"/>
    10.         </Grid>
    11.     </ControlTemplate>
    12. </ResourceDictionary>

    引用:
    1. <Page
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    4.     <!--リソース-->
    5.     <Page.Resources>
    6.         <ResourceDictionary>
    7.             <ResourceDictionary.MergedDictionaries>
    8.                 <ResourceDictionary Source="button.xaml"/>
    9.             </ResourceDictionary.MergedDictionaries>
    10.         </ResourceDictionary>
    11.     </Page.Resources>
    12.     <StackPanel>
    13.         <Button Width="100" Height="100" Template="{StaticResource EllipseButton}">
    14.         ボタン
    15.         </Button>
    16.     </StackPanel>
    17. </Page>
  28. ボタンのアニメーション効果(Silverlight)

    1. <UserControl x:Class="sla_anim_button1.Page"
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    4.     Width="400" Height="300">
    5.     <UserControl.Resources>
    6.         <ControlTemplate x:Key="EllipseButton1" TargetType="Button"
    7.             xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows">
    8.             <Grid>
    9.                 <vsm:VisualStateManager.VisualStateGroups>
    10.                     <vsm:VisualStateGroup x:Name="CommonStates">
    11.                         <vsm:VisualState x:Name="Normal" />
    12.                         <vsm:VisualState x:Name="MouseOver">
    13.                             <Storyboard>
    14.                                 <ColorAnimation Storyboard.TargetName="inside1" 
    15.                               Storyboard.TargetProperty="Color" To="Cyan" />
    16.                             </Storyboard>
    17.                         </vsm:VisualState>
    18.                         <vsm:VisualState x:Name="Pressed">
    19.                             <Storyboard >
    20.                                 <ColorAnimation Storyboard.TargetName="inside1" 
    21.                               Storyboard.TargetProperty="Color" To="#ff000000"/>
    22.                             </Storyboard>
    23.                         </vsm:VisualState>
    24.                     </vsm:VisualStateGroup>
    25.                 </vsm:VisualStateManager.VisualStateGroups>
    26.                 <Ellipse Fill="Red"/>
    27.                 <Ellipse Margin="8">
    28.                     <Ellipse.Fill>
    29.                         <SolidColorBrush x:Name="inside1" Color="Green"/>
    30.                     </Ellipse.Fill>
    31.                 </Ellipse>
    32.                 <ContentPresenter HorizontalAlignment="Center" 
    33.                                   VerticalAlignment="Center"/>
    34.             </Grid>
    35.         </ControlTemplate>
    36.     </UserControl.Resources>
    37.     <Grid x:Name="LayoutRoot" Background="White" Loaded="LayoutRoot_Loaded">
    38.         <Button Width="100" Height="100" Template="{StaticResource EllipseButton1}" Content="ボタン"/>
    39.     </Grid>
    40. </UserControl>
  29. XamlReader(SilverLight)
    1. <UserControl x:Class="sla_xamlreader1.Page"
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    4.     Width="400" Height="300">
    5.     <Grid x:Name="LayoutRoot" Background="White" Loaded="LayoutRoot_Loaded" >
    6.     </Grid>
    7. </UserControl>


    1. private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
    2. {
    3.     StackPanel sp = (StackPanel)System.Windows.Markup.XamlReader.Load(
    4.         "<StackPanel "
    5.         + "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" />");
    6.     LayoutRoot.Children.Add(sp);
    7.     for (int i = 0; i < 5; i++)
    8.     {
    9.         string xaml = string.Format("<TextBlock "
    10.             + "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" "
    11.             +"Text=\"ここは、 {0} 番目\"/>", i);
    12.         TextBlock ctrl = (TextBlock)System.Windows.Markup.XamlReader.Load(xaml);
    13.         sp.Children.Add(ctrl);
    14.     }
    15. }
  30. リソース(スタイル)をコードで設定する(Silverlight)
    Silverlightでは、ResourceDirectoryにSourceプロパティがなく、XAMLファイルを読み込めない。この代案にXamlReaderを使うことを考える。
    1.リソースをコードで追加する方法
    2.XAML形式からリソースを追加する方法
    3.コードでリソースを参照する方法
    4.XAML形式でリソースを参照する方法
    1. readonly string XMLNS = " xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\""
    2.                       + " xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" ";
    3. private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
    4. {
    5.     //コードでリソースを追加する
    6.     Style style1 = new Style(typeof(TextBlock));
    7.     style1.Setters.Add(new Setter(TextBlock.ForegroundProperty, new SolidColorBrush(Colors.Red)));
    8.     App.Current.Resources.Add("style1", style1);
    9.     //XAML形式からリソースを追加する
    10.     Style style2 = (Style)XamlReader.Load(
    11.             "<Style" + XMLNS + "TargetType=\"TextBlock\"> "
    12.             + "<Setter Property=\"Foreground\" Value=\"Red\"/> " 
    13.             + "</Style>"); 
    14.     App.Current.Resources.Add("style2", style2);
    15.     //スタックパネルを追加する
    16.     StackPanel sp = new StackPanel();
    17.     LayoutRoot.Children.Add(sp);
    18.     //コードでリソースを参照する
    19.     TextBlock tb1 = new TextBlock();
    20.     tb1.Style = (Style)App.Current.Resources["style1"];
    21.     tb1.Text = "スタイルの作用で赤い文字になる。";
    22.     sp.Children.Add(tb1);
    23.     //XAML形式でリソースを参照する
    24.     TextBlock tb2 = (TextBlock)XamlReader.Load("<TextBlock" + XMLNS
    25.         + " Style=\"{StaticResource style2}\" "
    26.         + "Text=\"スタイルの作用で赤い文字になる。\" />");
    27.     sp.Children.Add(tb2);
    28. }
  31. スタイルを別なファイルからロードする(Silverlight)
    Silverlightでは、ResourceDirectoryにSourceプロパティがなく、XAMLファイルを読み込めない。この代案にXamlReaderを使うことを考える。
    サンプルの実行:sla_xamlreader1
    1.アプリケーション(ページ)では、LoadStyles()を呼び出す。
    Page.xaml.cs
    1. using System.Windows;
    2. using System.Windows.Controls;
    3. using System.Windows.Markup;
    4. namespace sla_xamlreader1
    5. {
    6.     public partial class Page : UserControl
    7.     {
    8.         public Page()
    9.         {
    10.             InitializeComponent();
    11.         }
    12.         readonly string XMLNS = " xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\""
    13.                               + " xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" ";
    14.         private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
    15.         {
    16.             LoadStyles("AppStyles.xml");
    17.             //スタックパネルを追加する
    18.             StackPanel sp = new StackPanel();
    19.             LayoutRoot.Children.Add(sp);
    20.             //コードでリソースを参照する
    21.             TextBlock tb1 = new TextBlock();
    22.             tb1.Style = (Style)App.Current.Resources["style1"];
    23.             tb1.Text = "スタイルの作用で赤い文字になる。";
    24.             sp.Children.Add(tb1);
    25.             //XAML形式でリソースを参照する
    26.             TextBlock tb2 = (TextBlock)XamlReader.Load("<TextBlock" + XMLNS
    27.                 + " Style=\"{StaticResource style2}\" "
    28.                 + "Text=\"スタイルの作用で緑の文字になる。\" />");
    29.             sp.Children.Add(tb2);
    30.         }
    31.     }
    32. }

    2.LoadStyles()は、指定されたXMLファイルからスタイルを読み込む。
        Silverlightの実行形式のxapは、フォルダをZIP圧縮したもの。
        ブラウザ側では、これを展開したフォルダがアクセスできる。
        (分離ストレージ)
        プロジェクトにXMLファイルを含めておけば、一緒にパックされ、
        ブラウザ側に送られる。 
    LoadStyles.cs
    1. using System.Windows.Controls;
    2. using System.Xml;
    3. using System.Windows.Markup;
    4. namespace sla_xamlreader1
    5. {
    6.     public partial class Page : UserControl
    7.     {
    8.         /// <summary>
    9.         /// XMLファイルに書かれたスタイルをApp.Current.Resourcesに追加します。
    10.         /// </summary>
    11.         /// <param name="fn">スタイルを記述したXMLファイルの名前</param>
    12.         void LoadStyles(string fn)
    13.         {
    14.             using (XmlReader reader = XmlReader.Create(fn))
    15.             {
    16.                 reader.MoveToContent();
    17.                 while (reader.ReadToFollowing("Style"))
    18.                 {
    19.                     App.Current.Resources.Add(
    20.                         reader.GetAttribute("x:Key"), 
    21.                         XamlReader.Load(reader.ReadOuterXml()));
    22.                 }
    23.             }
    24.         }
    25.     }
    26. }
    3.スタイルは以下のように定義した。
    AppStyles.xml
    1. <?xml version="1.0" encoding="utf-8" ?>
    2. <ResourceDictionary
    3.   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    4.   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    5.     <Style x:Key="style1" TargetType="TextBlock">
    6.         <Setter Property="Foreground" Value="Red"/>
    7.     </Style>
    8.     <Style x:Key="style2" TargetType="TextBlock">
    9.         <Setter Property="Foreground" Value="Green"/>
    10.     </Style>
    11.     <Style x:Key="style3" TargetType="TextBlock">
    12.         <Setter Property="Foreground" Value="Blue"/>
    13.     </Style>
    14. </ResourceDictionary>

    4.Page.xaml
    1. <UserControl x:Class="sla_xamlreader1.Page"
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    4.     Width="400" Height="300">
    5.     <Grid x:Name="LayoutRoot" Background="White" 
    6.           Loaded="LayoutRoot_Loaded" >
    7.     </Grid>
    8. </UserControl>
  32. ボタンのサンプル

    sla_button1

      Silverlightアプリケーションでは、プロジェクトに含まれるXMLファイルがxapに同梱される。
      ボタンなどのスタイルをXMLファイルに記述して再利用できるようにする。
      実行時に読み込むので、ページを記述したXAMLファイルでは参照を記述できない。現状では、XAMLにはスタイルを適用するコントロールに名前を付け、ビハインドコードでスタイルを設定している。これは工夫の余地がある。

      コントロールの装飾には以下のような方法がある。
    1)アニメーション
    2)形状(矩形以外に。枠を複数の線で。色を変えて。)
    3)グラデーション

      ボタンの上にマウスが来ると変化すると言った使い方。WPFの場合はトリガを記述する方法で実現しておりアニメーションではない。
      形状は、Borderがよく使われる。Ellipse、Rectangleでも良い。コーナーに丸みを付けるCornerRadiusプロパティで四隅を独立して設定できる。それを重ねることができる。
      グラデーションは立体感を作る効果がある。
    1. <?xml version="1.0" encoding="utf-8" ?>
    2. <ResourceDictionary
    3.   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    4.   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    5.     <Style x:Key="TITLE_1" TargetType="TextBlock">
    6.         <Setter Property="Foreground" Value="Red"/>
    7.         <Setter Property="FontSize" Value="24"/>
    8.     </Style>
    9.     <Style x:Key="TEXT_1" TargetType="TextBlock">
    10.         <Setter Property="Foreground" Value="Black"/>
    11.         <Setter Property="FontSize" Value="12"/>
    12.         <Setter Property="TextWrapping" Value="Wrap"/>
    13.     </Style>
    14.     <Style x:Key="AnimEllipseButton1" TargetType="Button">
    15.         <Setter Property="Template">
    16.             <Setter.Value>
    17.                 <ControlTemplate x:Name="CT_AEBT1" TargetType="Button"
    18.                 xmlns:y0="clr-namespace:System.Windows;assembly=System.Windows">
    19.                     <Grid>
    20.                         <y0:VisualStateManager.VisualStateGroups>
    21.                             <y0:VisualStateGroup x:Name="CommonStates">
    22.                                 <y0:VisualState x:Name="Normal" />
    23.                                 <y0:VisualState x:Name="MouseOver">
    24.                                     <Storyboard>
    25.                                         <ColorAnimation Storyboard.TargetName="inside1"
    26.                                           Storyboard.TargetProperty="Color" To="Cyan" />
    27.                                     </Storyboard>
    28.                                 </y0:VisualState>
    29.                                 <y0:VisualState x:Name="Pressed">
    30.                                     <Storyboard >
    31.                                         <ColorAnimation Storyboard.TargetName="inside1"
    32.                                            Storyboard.TargetProperty="Color" To="#ff000000"/>
    33.                                     </Storyboard>
    34.                                 </y0:VisualState>
    35.                             </y0:VisualStateGroup>
    36.                         </y0:VisualStateManager.VisualStateGroups>
    37.                         <Ellipse Fill="Red"/>
    38.                         <Ellipse Margin="8">
    39.                             <Ellipse.Fill>
    40.                                 <SolidColorBrush x:Name="inside1" Color="Green"/>
    41.                             </Ellipse.Fill>
    42.                         </Ellipse>
    43.                         <ContentPresenter HorizontalAlignment="Center"
    44.                               VerticalAlignment="Center"/>
    45.                     </Grid>
    46.                 </ControlTemplate>
    47.             </Setter.Value>
    48.         </Setter>
    49.     </Style>
    50.     <Style x:Key="GradientButton1" TargetType="Button">
    51.         <Setter Property="Foreground" Value="DarkRed"/>
    52.         <Setter Property="FontWeight" Value="Bold"/>
    53.         <Setter Property="Template">
    54.             <Setter.Value>
    55.                 <ControlTemplate TargetType="Button" xmlns:y0="clr-namespace:System.Windows;assembly=System.Windows">
    56.                     <Grid>
    57.                         <y0:VisualStateManager.VisualStateGroups>
    58.                             <y0:VisualStateGroup x:Name="CommonStates">
    59.                                 <y0:VisualState x:Name="MouseOver">
    60.                                     <Storyboard>
    61.                                         <ColorAnimationUsingKeyFrames Duration="00:00:00.001"
    62.                                           Storyboard.TargetName="border1"
    63.                                           Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)">
    64.                                             <SplineColorKeyFrame KeyTime="00:00:00" Value="#ccffffff"/>
    65.                                         </ColorAnimationUsingKeyFrames>
    66.                                     </Storyboard>
    67.                                 </y0:VisualState>
    68.                                 <y0:VisualState x:Name="Pressed">
    69.                                     <Storyboard>
    70.                                         <ColorAnimationUsingKeyFrames Duration="00:00:00.001" 
    71.                                           Storyboard.TargetName="border1" 
    72.                                           Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)">
    73.                                             <SplineColorKeyFrame KeyTime="00:00:00" Value="#c0ee80ee"/>
    74.                                         </ColorAnimationUsingKeyFrames>
    75.                                     </Storyboard>
    76.                                 </y0:VisualState>
    77.                                 <y0:VisualState x:Name="Disabled"/>
    78.                                 <y0:VisualState x:Name="Normal"/>
    79.                             </y0:VisualStateGroup>
    80.                         </y0:VisualStateManager.VisualStateGroups>
    81.                         <Border x:Name="border1" BorderBrush="Cyan" BorderThickness="3" CornerRadius="16,4,16,4">
    82.                             <Border.Background>
    83.                                 <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
    84.                                     <GradientStop Color="White" Offset="0"/>
    85.                                     <GradientStop Color="Gray" Offset="0.5"/>
    86.                                     <GradientStop Color="Black" Offset="1"/>
    87.                                 </LinearGradientBrush>
    88.                             </Border.Background>
    89.                         </Border>
    90.                         <Border Opacity="0.25" BorderBrush="White" BorderThickness="11,11,11,11" CornerRadius="16,4,16,4"/>
    91.                         <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
    92.                     </Grid>
    93.                 </ControlTemplate>
    94.             </Setter.Value>
    95.         </Setter>
    96.     </Style>
    97.     <Style x:Key="GlassButton1" TargetType="Button">
    98.         <Setter Property="Template">
    99.             <Setter.Value>
    100.                 <ControlTemplate TargetType="Button"
    101.                     xmlns:y0="clr-namespace:System.Windows;assembly=System.Windows">
    102.                     <Grid>
    103.                         <!--ボタンの外枠-->
    104.                         <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" RadiusX="20" RadiusY="20" StrokeThickness="5" Fill="Transparent">
    105.                             <Rectangle.Stroke>
    106.                                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
    107.                                     <GradientStop Color="Gray" Offset="0" />
    108.                                     <GradientStop x:Name="outside_color" Color="DarkGray" Offset="0.3" />
    109.                                     <GradientStop Color="Gray" Offset="1" />
    110.                                 </LinearGradientBrush>
    111.                             </Rectangle.Stroke>
    112.                         </Rectangle>
    113.                         <!--ボタンの内側-->
    114.                         <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stroke="Transparent" StrokeThickness="20" RadiusX="20" RadiusY="20">
    115.                             <Rectangle.Fill>
    116.                                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
    117.                                     <GradientStop Color="Gray" Offset="0" />
    118.                                     <GradientStop x:Name="inside_color" Color="DarkGray" Offset="0.3" />
    119.                                     <GradientStop Color="Gray" Offset="1" />
    120.                                 </LinearGradientBrush>
    121.                             </Rectangle.Fill>
    122.                         </Rectangle>
    123.                         <!--アニメーションで透明度を操作する表面-->
    124.                         <Rectangle x:Name="surface" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" StrokeThickness="2" RadiusX="10" RadiusY="10" Opacity="0" RenderTransformOrigin="0.5,0.5">
    125.                             <Rectangle.Stroke>
    126.                                 <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
    127.                                     <LinearGradientBrush.GradientStops>
    128.                                         <GradientStop Offset="0.0" Color="White" />
    129.                                         <GradientStop Offset="1.0" Color="Gray" />
    130.                                     </LinearGradientBrush.GradientStops>
    131.                                 </LinearGradientBrush>
    132.                             </Rectangle.Stroke>
    133.                             <Rectangle.Fill>
    134.                                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" Opacity="0.75">
    135.                                     <GradientStopCollection>
    136.                                         <GradientStop Color="WhiteSmoke" Offset="0.0" />
    137.                                         <GradientStop Color="Transparent" Offset="0.5" />
    138.                                         <GradientStop Color="WhiteSmoke" Offset="0.6" />
    139.                                         <GradientStop Color="Transparent" Offset="0.8" />
    140.                                         <GradientStop Color="WhiteSmoke" Offset="0.9" />
    141.                                         <GradientStop Color="Transparent" Offset="1" />
    142.                                     </GradientStopCollection>
    143.                                 </LinearGradientBrush>
    144.                             </Rectangle.Fill>
    145.                             <Rectangle.RenderTransform>
    146.                                 <TransformGroup>
    147.                                     <ScaleTransform x:Name="surface_scale"  ScaleX="1" ScaleY="1"/>
    148.                                 </TransformGroup>
    149.                             </Rectangle.RenderTransform>
    150.                         </Rectangle>
    151.                         <!--ボタンの文字部分の描画設定-->
    152.                         <ContentPresenter HorizontalAlignment="Center"
    153.                           VerticalAlignment="Center"/>
    154.                         <!--アニメーション-->
    155.                         <y0:VisualStateManager.VisualStateGroups>
    156.                             <y0:VisualStateGroup x:Name="CommonStates">
    157.                                 <y0:VisualState x:Name="MouseOver">
    158.                                     <Storyboard>
    159.                                         <ColorAnimation Storyboard.TargetName="outside_color"
    160.                                             Storyboard.TargetProperty="Color" To="#303030" Duration="0:0:0.001" />
    161.                                         <ColorAnimation Storyboard.TargetName="inside_color"
    162.                                             Storyboard.TargetProperty="Color" To="DodgerBlue" Duration="0:0:0.001" />
    163.                                         <DoubleAnimation Storyboard.TargetName="surface"
    164.                                             Storyboard.TargetProperty= "Opacity" To="1" Duration="0:0:0.001" />
    165.                                         <DoubleAnimation Storyboard.TargetName="surface_scale"
    166.                                             Storyboard.TargetProperty="ScaleX" From="1" To="0.9" Duration="0:0:0.5"/>
    167.                                         <DoubleAnimation Storyboard.TargetName="surface_scale"
    168.                                             Storyboard.TargetProperty="ScaleY" From="1" To="0.9" Duration="0:0:0.5"/>
    169.                                     </Storyboard>
    170.                                 </y0:VisualState>
    171.                                 <y0:VisualState x:Name="Disabled"/>
    172.                                 <y0:VisualState x:Name="Normal"/>
    173.                             </y0:VisualStateGroup>
    174.                         </y0:VisualStateManager.VisualStateGroups>
    175.                     </Grid>
    176.                 </ControlTemplate>
    177.             </Setter.Value>
    178.         </Setter>
    179.     </Style>
    180. </ResourceDictionary>
  33. 文章を表示するには、TextBlockよりFlowDocumentを使うらしい。
    TextBlockの不利な点:
    1)コンテンツとして記述した場合、字下げができない。
    2)Text=""で記述すると字下げできるが改行が問題
    3)ドキュメントにあるようなVerticalContentAlignmentが設定できない
  34. FlowDocument は、Silverlight では使えない
    1. <TextBlock Text="  ">字下げの<LineBreak/>テスト</TextBlock>
    で、段落の字下げをする。 
  35. コンソール風の表示
    1. <Style TargetType="TextBox">
    2.     <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
    3.     <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
    4.     <Setter Property="AcceptsReturn" Value="True"/>
    5. </Style>

    1.      :
    2. <TextBox Name="textBox1" xml:space="preserve" />
    3.      :
    4. <TextBox Name="textBox2" IsReadOnly="True" />
    5.      :
  36. ウインドウの相対割付
    1. <Grid.RowDefinitions>
    2.     <RowDefinition Height="Auto"/>
    3.     <RowDefinition Height=".5*"/>
    4.     <RowDefinition Height=".5*"/>
    5.     <RowDefinition Height="Auto"/>
    6. </Grid.RowDefinitions>
    7. <Grid.ColumnDefinitions>
    8.     <ColumnDefinition Width=".5*"/>
    9.     <ColumnDefinition Width=".5*"/>
    10. </Grid.ColumnDefinitions>
    リサイズしても、上下、左右に均等に2分割。最初と最後の行は表示内容でサイズが決まる。
  37. 「開く」メニューを表示する
    1. <Window.CommandBindings>
    2.     <CommandBinding Command="ApplicationCommands.Open" Executed="CommandBinding_Executed"/>
    3. </Window.CommandBindings>

    1.        <Menu>
    2.            <MenuItem Command="ApplicationCommands.Open"/>
    3.        </Menu>

    1. private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
    2. {
    3.     OpenFileDialog ofd = new OpenFileDialog();
    4.     ofd.Filter = "Images|*.jpg;*.png;*.bmp;*.gif|All Files|*.*";
    5.     if (ofd.ShowDialog(this) == true)
    6.     {
    7.         img.Source = new BitmapImage(new Uri(ofd.FileName));
    8.     }
    9. }
  38. ComboBox
    1)選択肢の記述
    <ComboBoxItem>選択肢1</ComboBoxItem>
           :
    2)最初の表示
    SelectedIndex="5"
    3)値の入力可否
    IsEditable="True"
  39. 普通のアプリケーション・ウインドウ
    Menu、StatusBar のある普通の窓
    1. <Window
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4.     x:Class="FlvMP3Gain2.Window1"
    5.     Title="Window1" Height="300" Width="420">
    6.     <Grid x:Name="grid1" Loaded="grid1_Loaded" Drop="grid1_Drop" AllowDrop="True">
    7.         <Grid.RowDefinitions>
    8.             <RowDefinition Height="Auto"/>
    9.             <RowDefinition Height="*"/>
    10.             <RowDefinition Height="Auto"/>
    11.         </Grid.RowDefinitions>
    12.         <Menu Grid.Row="0" VerticalAlignment="Top">
    13.             <MenuItem Header="メニュー項目1" Click="ffmpeg_info_Click"/>
    14.         </Menu>
    15.         <Grid Grid.Row="1">
    16.             :
    17.         </Grid>
    18.         <StatusBar Grid.Row="2">
    19.             <DockPanel>
    20.                 <Label Content="ssssss"/>
    21.             </DockPanel>
    22.         </StatusBar>
    23.     </Grid>
    24. </Window>
    あるいは、
    1. <Window
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4.     xmlns:WpfToolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
    5.     x:Class="FlvMP3Gain2.Window1"
    6.     Title="Window1" Height="300" Width="420" >
    7.     <DockPanel Name="dockPanel1" Loaded="dockPanel1_Loaded" Drop="dockPanel1_Drop" AllowDrop="True">
    8.         <Menu DockPanel.Dock="Top">
    9.             <MenuItem Header="ffmpeg情報" Click="ffmpeg_info_Click"/>
    10.         </Menu>
    11.         <StatusBar DockPanel.Dock="Bottom">
    12.             <DockPanel>
    13.                 <Label Content="ssssss"/>
    14.             </DockPanel>
    15.         </StatusBar>
    16.         <Grid>
    17.             :
    18.         </Grid>
    19.     </DockPanel>
    20. </Window>
  40. OK,Cancel ボタンとEnter、Escキーの同一視
    Button のIsDefault、IsCancel をTrueにすると、それぞれ、Enter、EscキーでClickイベントが発生する。
  41. ListView で、GridViewColumn のHeaderにビハインドコードで、文字列を代入したとき、アンダースコアが無視されて詰まって表示される。データーベースからDataSetにFillした項目名がアンダースコアなしで表示されているので気が付いた。TextBlockに文字列を設定して、header には TextBlock を代入した。

     


mikeo_410@hotmail.com