WPF 資源設定 引用資源字典
<Window x:Class="WpfDemo.ResourceDemo" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfDemo" xmlns:sys="clr-namespace:System;assembly=mscorlib" mc:Ignorable="d" Title="ResourceDemo" Height="300" Width="300"> <Window.Resources> <ResourceDictionary Source="ResourceDemo2.xaml"> <!--引用資源字典--> </ResourceDictionary> </Window.Resources> <Grid> <Grid.Resources> <ResourceDictionary> <sys:String x:Key="str2"> 今天天氣不太好 </sys:String> </ResourceDictionary> </Grid.Resources> <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="24" Margin="35,52,0,0" TextWrapping="Wrap" Text="{StaticResource str1}" VerticalAlignment="Top" Width="120"/> <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="35,97,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="26" Width="120"/> </Grid> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace WpfDemo { /// <summary> /// ResourceDemo.xaml 的互動邏輯 /// </summary> public partial class ResourceDemo : Window { public ResourceDemo() { InitializeComponent(); //string str=this.FindResource("str1").ToString(); // 後台尋找資源 string str = this.Resources["ss1"].ToString(); this.textBlock.Text = str; } } }
資源字典
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfDemo" xmlns:sys="clr-namespace:System;assembly=mscorlib"> <sys:String x:Key="ss1"> 資源字典1 </sys:String> <sys:Double x:Key="dd1"> 3.1412596 </sys:Double> <sys:String x:Key="str1"> 今天天氣真好 </sys:String> </ResourceDictionary>