WPF Resource用法

Posted by Leo Yang on 2020-07-02

Resource類型

Resource Property

Style

1
2
3
4
5
6
7
8
9
10
<Window>
<!-- 定義checkbox樣式 CheckBoxStyle-->
<Window.Resources>
<Style TargetType="{x:Type CheckBox}" x:Key="CheckBoxStyle">
<Setter Property="Background" Value="Red"/>
</Style>
</Window.Resources>
<!-- 套用樣式CheckBoxStyle -->
<CheckBox IsChecked="{Binding Path=Data.Result}" Style="{StaticResource CheckBoxStyle}"/>
</Window>

Template

1
2
3
4
5
6
7
8
9
10
<Window>
<Windows.Resource>
<!-- 定義DataTemplate service -->
<Datatemplate x:key="service">
<Textbox Text="{Binding ServiceName}"/>
</Datatemplate>
</Windows.Resource>
<!-- Listbox Itemtamplate屬性 套用 service datatemplate -->
<ListBox ItemTemplate="{StaticResource Service}" itemsource="{binding DataSource}"/>
</Window>

宣告靜態資源

1
2
3
4
5
6
7
8
9
<Window>
<Windows.Resource>
<!-- 在Resource 中宣告ViewModel Instance -->
<local:ViewModel x:Key="MainData">
</Windows.Resource>
<Grid DataContext="{Binding Source={StaticResource MainData}}">
<!-- .... -->
</Grid>
</Window>

Global Resource

App.Xaml

把Resource寫到App.xaml,這樣專案下的所有元件都可以用

Resource Dinctionary

Dictionary.xaml

1
2
3
4
5
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:yourproject">

</ResourceDictionary>

Resource Dictionary