2014-03-19 54 views
-1

我想根据我的字符串的长度在正确的字体大小的文本块中显示字符串,所以我想也许通过计数字符串长度或字符,然后更新我的字体大小,但我不知道该怎么办在代码....计数字符串字符mvvm

回答

1
<Style x:Key="ApplicationNameStyle" TargetType="TextBlock"> 
     <Setter Property="FontSize" Value="{Binding FontSize,Mode=TwoWay, Source={StaticResource Sampe}}"/> 
     <Setter Property="FontWeight" Value="Bold"/> 
     <Setter Property="Margin" Value="0,2,0,0"/> 
     <Setter Property="VerticalAlignment" Value="Center"/> 
     <Setter Property="Effect"> 
      <Setter.Value> 
       <DropShadowEffect BlurRadius="10" Opacity="0.25" ShadowDepth="0"/> 
      </Setter.Value> 
     </Setter> 
    </Style> 

Viewmodel.cs

public Double FontSize 
{ 
    get 
    { 
     return _fontSize; 
    } 
    set 
    { 
     _fontSize = value; 
     put your logic! 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs("FontSize")); 
    } 
} 
+0

绑定或属性名称错误。两者都应引用相同的属性('FontSize12'或'FontSize1') –

+0

是修改答案! – Sajeetharan

1

您也可以使用Converter这样

public class TextFontSizeConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     int size; 
     //value is MyText 
     //Your logic to calculate the font size; 
     ... 
     return size; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

在视图中,声明在资源部分中的转换器:

<local:TextFontSizeConverter x:Key="Converter"/> 

然后,其绑定到TextBlock

<TextBlock Text="{Binding MyText, Mode=TwoWay}" FontSize="{Binding MyText, Mode=TwoWay, Converter={StaticResource Converter}}" /> 

通过该解决方案,可以随时重新使用逻辑与任何TextBlock的。