实例介绍
1. 添加两个textbox,第一个textbox从XMAL资源中获取字符串,第二个textbox从C#中获取资源
2. 为了在XMAL中使用string类,需要引用
xmlns:sys="clr-namespace:System;assembly=mscorlib"
3. 类型转换
this.FindResource("myString") as string
等效于
(string)this.FindResource("myString")
XMAL源码
<Window x:Class="WpfApp8.MainWindow"
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:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApp8"
mc:Ignorable="d"
Title="MainWindow" Height="130" Width="200">
<Window.Resources>
<sys:String x:Key="myString">hello wpf</sys:String>
</Window.Resources>
<StackPanel>
<TextBox Text="{StaticResource myString}"/>
<TextBox Name="textBox1" />
<Button Name="btnCtrl1" Content="show" Margin="5" Click="BtnCtrl1_Click"/>
</StackPanel>
</Window>
C#源码
using System.Windows;
namespace WpfApp8
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void BtnCtrl1_Click(object sender, RoutedEventArgs e)
{
string str = this.FindResource("myString") as string;
this.textBox1.Text = str;
}
}
}
除了在窗口定义资源外,还可以在应用程序定义资源
窗口不是查找应用程序资源的最后一站,如果在控件或其他容器中知道包含窗口或页面找不到指定的资源。WPF会继续查找为应用程序定义的资源。在Visual Studio中,这些资源在App.xaml文件的标记中定义的资源。
<Application x:Class="WpfApp8.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApp8"
StartupUri="MainWindow.xaml">
<Application.Resources>
<sys:String x:Key="myString">hello wpf</sys:String>
</Application.Resources>
</Application>
运行效果