MVVM正常就是在View頁面寫樣式,ViewModel頁面寫邏輯,但是有的時候純在View頁面寫樣式並不能滿足需求。我最近的這個項目就遇到了,因此只能在VM頁面去寫樣式控件,然后綁定到View頁面。
先看圖
各種稅是需要變動的,當然,並不是由於這個原因才在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(20, 0, 20, 0); textblock.FontSize = 30; 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 = 0; 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"/>