资源

基础点

WPF支持传统资源,还支持对象级资源,每个元素可以携带自己的资源;

    资源都是字典形式  

   对象级资源的定义与查找

   <Window x:Class="WpfApplication2.command1"

        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:WpfApplication2"

        xmlns:sys="clr-namespace:System;assembly=mscorlib"

        mc:Ignorable="d"

        Title="command1" Height="300" Width="300">

    <Window.Resources>

        <sys:String x:Key="name">人才</sys:String>

        <sys:Double x:Key="age">25</sys:Double>

    </Window.Resources>

    <Grid x:Name="grid1"  >

        <TextBox x:Name="textBox"  Text="{StaticResource name}"  /> 

        <!--数值形资源只能用到数值的属性去-->

        <Slider x:Name="slider"  Minimum="{StaticResource age}"/>

    </Grid> 

</Window>

<!--{StaticResource name}key="name"的资源会一层一层往外查找,直到程序给App.xml里定义的,如果都找不到就会报异常-->

C#的查找写法:textBox.Text=this.FindResource("name").ToString();

资源很多时可以单独出一个文件

      <Window.Resources>

        <ResourceDictionary Source="red.xaml"></ResourceDictionary> 

 </Window.Resources>

  动静态资源

    <Window.Resources> 

        <sys:String x:Key="name">人才</sys:String>

        <sys:String x:Key="name2">人才2</sys:String> 

    </Window.Resources>

    <Grid x:Name="grid1"  >

        <TextBox x:Name="textBox" Text="{StaticResource name}"  >

        <TextBox x:Name="textBox2" Text="{DynamicResource name2}"  />

       <!--如果通过button点击事件等改变了name2的值,那么{DynamicResource name2}则会自动改变-->

    </Grid> 

 添加二进制资源

文本资源

  

xaml读取:

<Window x:Class="WpfApplication2.command1"

        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:WpfApplication2"

        xmlns:prop="clr-namespace:WpfApplication2.Properties"

        xmlns:sys="clr-namespace:System;assembly=mscorlib"

        mc:Ignorable="d"

        Title="command1" Height="300" Width="300"> 

    <Grid x:Name="grid1"  >

        <TextBox x:Name="textBox" Text="{x:Static prop:Resources.Name}" /> 

    </Grid> 

</Window>

C#读取:

 textBox.Text = Properties.Resources.Name.ToString();

Resources.resx多用于做多语言

图片语音资源

 

或者当做文件带过去

 

<Image x:Name="image" Source="test.jpg"/>

若为二进制,其读法也如上,直接使用路径即可。只是C#读法不一样

      Uri imgUri = new Uri(@"test.jpg", UriKind.Relative);

 image.Source = new BitmapImage(imgUri);

原文地址:https://www.cnblogs.com/evemen/p/6239335.html