资源
资源就是有用的数据,很多地方需要存储数据。
核心数据存储到数据库
配置信息配置文件
系统使用的图标/图片可以编译到程序集中。
在WPF中,每个控件都可以存储数据。
数据库的数据是仓库,资源文件是行李箱,控件的数据是随身携带的背包,
变量的数据拿在手里。
Resources 属性,来自于FramwworkElement中,对象类型是ResourceDictionary,使用键值对存储资源和查找资源。
资源的使用非常灵活。
<Grid > <Grid.Resources> <sys:String x:Key="tb">测试数据啦啦啦</sys:String> </Grid.Resources> <StackPanel> <Button Content="{StaticResource tb}" Width="100" Height="30"></Button> </StackPanel>
</Grid> |
Static 静态资源 程序启动后只访问一次。
Dynamic 动态资源 程序启动后可以多次访问。
动态对资源赋值,由于是Dynamic,赋值后的资源,立刻就更新到内容上了。
<Grid x:Name="gd"> <Grid.Resources> <sys:String x:Key="tb">测试数据啦啦啦</sys:String> </Grid.Resources> <StackPanel> <Button Content="{DynamicResource tb}" Width="100" Height="30" Click="Button_Click"></Button> </StackPanel>
</Grid>
private void Button_Click(object sender, RoutedEventArgs e) { gd.Resources["tb"] = "哈哈哈";//资源是字典 }
|
资源的查找:
FindResource(“Key”)
二进制资源的路径:
Pack URI:
完整路径:
Pack://application,,,[/程序集名称;][可选版本号;][文件夹名称/][文件名称]
可以简写为[文件夹名称/][文件名称]
下面是几种写资源图片的方式,XAML方式,c#代码相对方式,绝对方式。
<StackPanel> <Button Width="100" Height="30" Click="Button_Click"> <Button.Content> <Image Source="Images/bg.png"></Image> </Button.Content> </Button>
<Button Width="100" Height="30" > <Button.Content> <Image Source="pack://application:,,,/Images/bg.png"></Image> </Button.Content> </Button>
<StackPanel Margin="30"> <Button Width="100" Height="30" x:Name="test">
</Button>
<Button Width="100" Height="30" x:Name="test2">
</Button> </StackPanel>
</StackPanel>
Uri uri = new Uri(@"Images/bg.png",UriKind.Relative); Image img = new Image(); img.Source = new BitmapImage(uri); this.test.Content = img;
Uri uri11 = new Uri(@"pack://application:,,,/Images/bg.png", UriKind.Absolute); Image img11 = new Image(); img11.Source = new BitmapImage(uri); this.test2.Content = img11;
|