如何动态绑定字体图标(iconfont)
下载矢量字体的方法不赘述了。
在xaml中代码:
<TextBlock Text="{Binding ImageSwitch1,ElementName=xThis}" FontFamily="/Images/#iconfont" Foreground="Red" FontSize="30" Margin="5">
</TextBlock>
注意:
我在这里写的ImageSwitch1是一个依赖属性 原因在于我自定义了一个用户控件,将ImageSwitch1当做依赖属性传递给MainWindow里面去。FontFamily在这里填写的是一个相对路径,前提是他们在一个工程下面就可以,如果在其他的工程下面就需要绝对路径,写法:“pack://application:,/xxx(xxx代表命名空间);component/Images/#iconfont”
依赖属性的声明:
public string ImageSwitch1
{
get { return (string)GetValue(ImageSwitch1Property); }
set { SetValue(ImageSwitch1Property, value); }
}
// Using a DependencyProperty as the backing store for ImageSwitch. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ImageSwitch1Property =
DependencyProperty.Register("ImageSwitch1", typeof(string), typeof(UserControl1), new PropertyMetadata("/Images/NoPress.png"));
MainWindow.xmal 中的代码
<local:UserControl1 Width="100" Height="50" TextContent="MyText" Click="UserControl1_Click" ImageSwitch1="{Binding ImageSwitch,ElementName=xThis}" FontWeight="Bold">
注意:ImageSwitch1是依赖属性 ,ImageSwitch是定义的普通公开属性。
下面是ImageSwitch的定义:
public string ImageSwitch { get; set; } = "\xe748";
**注意:下载好的矢量图标下载下来,若不需要绑定的话,则可以直接使用Text = “"的方法,但是若想要绑定到后台,在后台.cs下面则需要改写成Text =”\xe748";将&#替换为\就可以了,注意这点。