WPF之获取资源方式

资源包括图片、xaml文件等
假设创建了一个工程为Demo
获取方式包括绝对路径/相对路径

相对路径

1.获取图片
new Uri("/Demo;component/Image/aaa.png", UriKind.Relative);
<Image Source="/Demo;component/Image/aaa.png"/>
2.获取xaml
new Uri("/Demo;component/Themes/aaa.xaml", UriKind.Relative);
3.代码中动态查找Style
比如在目录Controls自定义了一个控件CustomControl

ResourceDictionary dic = new ResourceDictionary();
            dic.Source = new Uri("/Demo;component/Controls/CustomControl.xaml",UriKind.Relative);
            Application.Current.Resources.MergedDictionaries.Add(dic);
            //以上几行代码表示将我们自定义的样式加载到应用程序的资源字典中。
            this.Style = (Style)Application.Current.Resources["CustomControlStyle"];

不加到应用程序字典时候

ResourceDictionary dic = new ResourceDictionary();
            dic.Source = new Uri("/Demo;component/Controls/CustomControl.xaml",UriKind.Relative);
            this.Style = (Style)dic ["CustomControlStyle"];

绝对路径

1.获取图片

new Uri("pack://application:,,,/Images/aaa.png")
<Image Source="pack://application:,,,/Images/aaa.png"/>

或者

new Uri("pack://application:,,,/Demo;component/Images/aaa.png")
<Image Source="pack://application:,,,/Demo;component/Images/aaa.png"/>

2.获取xaml
new Uri("pack://application:,,,/Themes/aaa.xaml")

xaml文件中引用别的xaml文件

<ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/Demo;component/Controls/other.xaml"/>
 </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

xaml中定义颜色

<Color x:Key="rmaryColor">#f3fbff</Color>
<SolidColorBrush x:Key="ForeColor" Color="#EFABDE"/>

代码中设置颜色

1.系统定义的颜色
AAABlockName.Foreground = Brushes.Yellow
2.设置颜色:
可以通过Color类中两个函数FromArgb/FromRgb设置颜色
Color.FromArgb(透明度, red数字, green数字, blue数字); //这四个数字范围都是(0-255)
Color.FromRgb(red数字, green数字, blue数字);//默认透明度为255;
例如
Color color = Color.FromArgb(0xff, 0xEF, 0xAB, 0x89)
3.Color转Brush
new SolidColorBrush(Color.FromArgb(0xff, 0xEF, 0xAB, 0x89))
new SolidColorBrush(Colors.AliceBlue)
4.string转换成Color/Brush:

Color color = (Color)ColorConverter.ConvertFromString("Red");
new SolidColorBrush(color )

5.Brush转换成Color

Color color= (Color)ColorConverter.ConvertFromString(brush.ToString());
Color color= ((SolidColorBrush)CadColor.Background).Color;

代码设置图片

var bitmapImage = new BitmapImage(new Uri($"/Demo;component/Images/pikaqiu2.png",UriKind.Relative));
ImageName.Source = bitmapImage;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容