MVVM正常就是在View页面写样式,ViewModel页面写逻辑,但是有的时候纯在View页面写样式并不能满足需求。我最近的这个项目就遇到了,因此只能在VM页面去写样式控件,然后绑定到View页面。

先看图

WPF MVVM框架下,VM界面写控件-LMLPHPWPF MVVM框架下,VM界面写控件-LMLPHP

各种税是需要变动的,当然,并不是由于这个原因才在VM页面写样式,而是因为不同的税是红色,相应的【】是黑色。

在Textblock里用Run属性来进行变量添加,而要给Run添加颜色时又是统一的,因此只能用三个Run来分别来设置“【”,“税种”,“】”,但是前台又没有办法进行解析,因此只能用VM页面进行书写样式。

字段

        private TextBlock textBlock;

        public TextBlock TextBlock
{
get { return textBlock; }
set { textBlock = value;
RaisePropertyChanged("TextBlock");
}
}

VM下的Textblock样式

TextBlock textblock = new TextBlock();
textblock.TextWrapping = TextWrapping.Wrap;
textblock.HorizontalAlignment = HorizontalAlignment.Center;
textblock.Margin = new Thickness(, , , );
textblock.FontSize = ;
textblock.HorizontalAlignment = HorizontalAlignment.Left;
textblock.VerticalAlignment = VerticalAlignment.Top; BrushConverter brushConverter = new BrushConverter();
Brush Blackbrush = (Brush)brushConverter.ConvertFromString("#2c2c2c");
Brush Redbrush = (Brush)brushConverter.ConvertFromString("#a80301"); textblock.Foreground = Blackbrush;
textblock.Inlines.Add(new Run() { Text = " ", Foreground = Brushes.Red });
textblock.Inlines.Add("您本月有");
for (int i = ; i < Mess.Count; i++)
{
textblock.Inlines.Add(new Run() { Text = "【", Foreground = Blackbrush });
textblock.Inlines.Add(new Run { Text = Mess[i].ToString(), Foreground = Redbrush });
textblock.Inlines.Add(new Run() { Text = "】", Foreground = Blackbrush });
}
textblock.Inlines.Add("税(费)种尚未申报,请在征期内申报。"); TextBlock = textblock;

XAML页面写个ScrollViewer接收一下就可以了

 <ScrollViewer Content="{Binding TextBlock}" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto"/>
04-20 22:40