2012年1月2日

WPF Templates


Style 只能就 element 已有的 property 設定,template 可以完全取代 element 的視覺外觀 (visual tree),而不會改變原有的功能與程式碼。Control templates 都是由 ControlTemplate class 所衍生的。

Control Templates

利用 ControlTemplate 定義 control 的外觀,並以 x:Key 設定 template 的名稱。
<Grid>
    <Grid.Resources>
        <ControlTemplate x:Key="buttonTemplate">
            <Grid Width="100" Height="30">
                <Rectangle Fill="Bisque" Stroke="Brown" RadiusX="5" RadiusY="5"/>
                <Ellipse Width="24" Height="24" Fill="Brown" HorizontalAlignment="Left" Margin="3"/>
            </Grid>
        </ControlTemplate>
    </Grid.Resources>
    <Button Template="{StaticResource buttonTemplate}"/>
</Grid>

Control Template Trigger

如同 style,template 也可以利用 trigger 來動態調整 control 的外觀。
<Grid>
    <Grid.Resources>
        <ControlTemplate x:Key="buttonTemplate">
            <Grid Width="100" Height="30">
                <Rectangle Fill="Bisque" Stroke="Brown" RadiusX="5" RadiusY="5"/>
                <Ellipse x:Name="Icon" Width="24" Height="24" Fill="Brown" HorizontalAlignment="Left" Margin="3"/>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="Button.IsMouseOver" Value="True">
                    <Setter TargetName="Icon" Property="Fill" Value="Red"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Grid.Resources>
    <Button Template="{StaticResource buttonTemplate}">OK</Button>
</Grid>

Restricting the Target Type

與 style 相同,template 也可以指定要套用的類別,但在  dictionary 中,不允許移除 x:Key 的設定。
<ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}">
    <Grid Width="100" Height="30">
        …
    </Grid>
</ControlTemplate>

Content Property

在前面的範例中,我們希望能顯示出原有 Button.Content 中的文字, 則可以透過 TemplateBinding 來達成。
<TextBlock Text="{TemplateBinding Content}" Margin="36,0,0,0" VerticalAlignment="Center"/>

不過要特別注意,Button 的 Content 不一定是文字型態,因此使用 ContentControl 或 ContentPresenter 是比較正確的寫法。ContentPresenter 比 ContentControl 輕些,因為 ControlControl 在 ContentPresenter 外面又包了一層物件。
<ContentPresenter Content="{TemplateBinding Content}"/>

Other Properties

除了 content property,也可以沿用原來物件的其他 property,例如 Background, FontSize,..等…。下列的範例,要特別注意,矩形的背景,直接使用 TemplateBinding 來達成,而圓形使用漸層上色,必須將 brush 轉換成 color,因此語法不同:
<ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}">
    <Grid Width="100" Height="30">
        <Rectangle Fill="{TemplateBinding Background}" Stroke="Brown" RadiusX="5" RadiusY="5"/>
        <Ellipse x:Name="Icon" Width="24" Height="24" HorizontalAlignment="Left" Margin="3">
            <Ellipse.Fill>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0, 1">
                    <GradientStop Offset="0"
                                    Color="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Foreground.Color}"/>
                    <GradientStop Offset="1" Color="Red"/>
                </LinearGradientBrush>
            </Ellipse.Fill>
        </Ellipse>
        <ContentPresenter Content="{TemplateBinding Content}" Margin="36,0,0,0" VerticalAlignment="Center"/>
    </Grid>
</ControlTemplate>
在上面的範例中,使用 Binding 取代 TemplateBinding,可以獲得更細密的內容。另外,在使用 trigger 時,因為是在 visual tree 外面動態處理,只能使用 Binding 而無法使用 TemplateBinding。

Control Parts

許多較複雜的 control 是由不同的 part 所組成,例如 ComboBox 由 PART_EditableTextBox 與 PART_Popup 組成。WPF 內建的 control 皆以 PART_xxx 命名。當設計 template 時,可能需要注意到這些細節。

Control States

在 WPF 4.0 之後,增加了 State 的設計,可以透過 VisualStateManager.GoToState 切換狀態。一個 control 可以有多個 state group,每個 group 又有多個 state。例如 Button 的 CommonStates group 包含了 Normal, MouseOver, Pressed, Disabled 四種狀態,而 FocusStates group 包含了 Unfocused, Focused 兩種狀態。在任何時候,Button 一定會在每一組 group 中的某個 state 中,例如 MouseOver & Focused。
設計 template 時,可以使用 <VisualStateManager.VirtualStateGroup> 來設計各種狀態的轉換方式。

Mixing Templates With Styles

將 template 設置在 style 中,可以用來取代 WPF 預設的 style,使用方式如下。注意在下列的範例中,ControlTemplate 可以不用 x:Key 來指定 template 的名稱。
<Grid>
    <Grid.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        …
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
    <Button>OK</Button>
</Grid>

WPF Styles


Sharing Styles

可以把不同 element 的 property 以 <Style x:Key=”…”> 集中在一起,如果 element 沒有這項 property,則會被忽略。
Example:
<StackPanel>
    <StackPanel.Resources>
        <Style x:Key="controlStyle">
            <Setter Property="Control.FontSize" Value="15"/>
            <Setter Property="Control.Height" Value="25"/>
            <Setter Property="Control.Width" Value="100"/>
            <Setter Property="Control.HorizontalAlignment" Value="Left"></Setter>
            <Setter Property="Control.VerticalAlignment" Value="Top"></Setter>
        </Style>
    </StackPanel.Resources>
    <Button Style="{StaticResource controlStyle}" Content="Button"   />
    <CheckBox Style="{StaticResource controlStyle}" Content="CheckBox" />
    <Rectangle Style="{StaticResource controlStyle}" Stroke="Black" />
</StackPanel>

Inherit

可以加入 BaseOn=”{..}” 來繼承其他的 style 設定:
<Style x:Key="controlStyleBold" BasedOn="{StaticResource controlStyle}">
    <Setter Property="Control.FontWeight" Value="Bold"/>
</Style>

Restricting the Styles

可以透過 TargetType=”{x:Type …}” 來限制 element 的類別:
<Style x:Key="controlStyle" TargetType="{x:Type Button}">
    <Setter Property="Control.FontSize" Value="15"/>
</Style>

Implicit Styles

上列的範例,若省略了前面的 x:Key,則會將所有 Button 的 style 都變更了。
<Style TargetType="{x:Type Button}">
    <Setter Property="Control.FontSize" Value="15"/>
</Style>

Property Triggers

可以透過 Style.Triggers 判斷 property 的數值,變動另一項 property 的內容:
<Style x:Key="controlStyle" TargetType="{x:Type Button}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="FontSize" Value="15"/>
        </Trigger>
    </Style.Triggers>
    <Setter Property="FontSize" Value="12"/>
    <Setter Property="Height" Value="25"/>
</Style>

Data Triggers

也可以經由資料內容動態改變 property:
<Style TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}" Value="1">
            <Setter Property="Background" Value="LightBlue"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

Logical OR Triggers

無論是 property trigger 或是 data trigger,都可以使用多項設定,來達到 or 效果:
<Style TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}" Value="1">
            <Setter Property="Background" Value="LightBlue"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}" Value="2">
            <Setter Property="Background" Value="LightCoral"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

Logical AND Triggers

如果想使用 and 產生 trigger,就必須使用 MultiTrigger 或 MultiDataTrigger指令:
<Style.Triggers>
    <MultiTrigger>
        <MultiTrigger.Conditions>
            <Condition Property="IsMouseOver" Value="True"/>
            <Condition Property="IsEnabled" Value="True"/>
        </MultiTrigger.Conditions>
        <Setter Property="Background" Value="AliceBlue"/>
    </MultiTrigger>
</Style.Triggers>

2011年9月8日

WPF Application

WPF Application 會使用到的一些基本功能

Command-line argument

應用程式的參數可以透過 string[] args = System.Environment.GetCommandLineArgs(); 來取得

 

Persisting and Restoring Application State

過去 Windows 的應用程式多半使用 Registry 或執行目錄中的檔案來存取,
WPF 則建議採用 isolated storage,除了更容易使用外,
也與 Silverlight Application, XAML Browser Application 能有一致性。
isolated storage 以隱藏檔,存放在 current user's Document 的目錄中。

儲存:
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myFile", System.IO.FileMode.Create, file))
{
    using (StreamWriter writer = new StreamWriter(stream))
    {… }
}

讀取:
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myFile", System.IO.FileMode.OpenOrCreate, file))
{
    using (StreamReader reader = new StreamReader(stream))
    {… }
}

Splash Screen

Splash Screen 是指程式載入前,所顯示的形象圖案,
在 WPF 中的設定十分簡單,只要將圖檔加入專案中,
然後將 Build Action 屬性設定為 SplashScreen 即可。

 

Deployment

有 Windows Installer 與 ClickOnce 兩種方式可以選擇,
Windows Installer 是以專案的方式加入方案,與 ClickOnce 比較,有下列好處:

  1. 可以設計安裝介面與安裝流程
  2. 可以掌控要安裝的所有檔案
  3. 可以將分享的組件,放置在 Global Assembly Cache
  4. 可以註冊 COM 元件
  5. 可以提供 user 選項,決定安裝的內容
  6. 可以透過 DVD 離線安裝

ClickOnce 則是直接在執行專案的 Publish 屬性表中,設定資料,然後直接佈署,
其優點如下:

  1. 採連線方式安裝,有自動更新版本與退版的功能
  2. 可以在每次網頁關閉時即清除,或安裝在本機中
  3. 檔案存放在獨立的區域,不會影響到其他軟體與檔案
  4. Uninstall 可以完整清除所有檔案 (Full-trust application 則不一定)
  5. 與 .NET code access security 整合,程式可以在權限受限下執行

 

WPF Browser Applications

在新增專案時,除了 WPF Application 外,還有另一種 WPF Browser Application,
或稱為 XAML Browser Application (XBAP)
使用 ClickOnce 的技術,可以直接在 browser 的畫面上執行。
ClickOnce 型態的 Application 為了有較好的效能,會以 cache 方式處理,
更新軟體時,必須增加 version number 編號,否則仍會執行 cache 上舊版本。
WPF Browser Application 僅有 Internet Zone 等級的權限,因此有許多限制;
例如無法存取 local file, Registry, 或開啟新的 window,並在 Firefox 中,
無法使用 WebBrowser。

如果要將 Application 改為 full-trust 等級,可以在專案的 Security 屬性頁中修改,
或依照下列步驟更改:

  1. 在 app.manifest 的 PermissionSet 加入 Unrestricted="true"
    <PermissionSet class=… ID="Custom" SameSite="Site" Unrestricted="true">
  2. 更改專案檔案 .csproj (or .vbproj),將 <TargetZone>Internet</TargetZone>
    改為<TargetZone>Custom</TargetZone>

2011年9月7日

WPF Binary Resource


WPF Resource 的學習筆記。

Package

  1. Embedded in assembly,適合 toolbar icon, logo 等圖案
    使用方法,是將檔案加入專案,將 Build Action 設定為 Resource
  2. 分離的外部檔,但是登記在程式中
    使用方法,也是將檔案加入專案,將 Build Action 設定為 Content
    另外,記得將 Copy to Output Directory 設為 Copy Always 或 Copy if newer
    可以在編譯時,自動依照專案中的目錄,存放到編譯好的環境中
  3. 執行階段才能知道的 resource,例如由使用者指定載入的圖片

Localize

  1. 和語系相關的 localizable resource
  2. 和語系無關的 language-neutral resource

Accessing Binary Resource

可以透過 uniform resource identifier (URI) 來指定 resource 位置
利入 <Image Width="32" Height = "32" Source="logo.png"/>
下列是各種使用狀況:
  1. Source=" Images/logo.png"
    說明:圖案位於 Images 目錄下的 logo.png
  2. Source="c:\Users\John\Documents\logo.png" or
    Source=file://c:/Users/John/Documents/logo.png
    說明:直接指定檔案在本機的目錄位置
  3. Source="http://myWebsite/image/logo.png"
    說明:圖檔位於網站上
  4. Source=" /MyDll;component/Images/Money.png"
    說明:圖檔位於 MyDll assembly 下的 images (僅適用 embedded)
  5. Source=" pack://siteOfOrigin:,,,/Images/logo.jpg"
    說明:圖檔位於所在位置的 images 子目錄下

Deploying Vue & .NET with Google OAuth on GCP Cloud Run

Deploying Vue & .NET with Google OAuth on GCP Cloud Run Deploying Vue & .NET with Google OAuth on GCP Cloud Run...