关于动态字符串的绑定
WPF的绑定实在是太强大了
1、正常情况下,我们的绑定是这样的,打印HelloWorld
<TextBlock Width="200" Height="30" FontSize="20" Text="{Binding Content}"/>
private string _content;
public string Content
{
get
{
return _content;
}
set { SetProperty<string>(ref _content, value); }
}
public PreviewStringViewModel()
{
Content = "HelloWorld";
}
而在必要的时候,我们需要对绑定的字符串进行处理,我这里只做简单处理,看似动态,实际静态,动态需要你们重新加一个动态规划,道理是一样的,我只是举个例子
2、现在开始打印HelloWorld!
<TextBlock Width="200" Height="30" FontSize="20" Text="{Binding Content}"/>
private string _content;
public string Content
{
get
{
return _content+"!";
}
set { SetProperty<string>(ref _content, value); }
}
public PreviewStringViewModel()
{
Content = "HelloWorld";
}
3、使用转换器
public class StringToConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string data)
{
return data + "!";
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<UserControl.Resources >
<cvt:StringToConverter x:Key="stringTo"/>
</UserControl.Resources>
<Grid>
<TextBlock
Width="200"
Height="30"
FontSize="20"
Text="{Binding Content, Converter={StaticResource stringTo}}" />
</Grid>
private string _content;
public string Content
{
get
{
return _content ;
}
set { SetProperty<string>(ref _content, value); }
}
public StringConverViewModel()
{
Content = "HelloWorld";
}
4、使用Stringformat
<TextBlock
Width="200"
Height="30"
FontSize="20"
Text="{Binding Content, StringFormat={}{0}!}" />
private string _content;
public string Content
{
get
{
return _content ;
}
set { SetProperty<string>(ref _content, value); }
}
public StringConverViewModel()
{
Content = "HelloWorld";
}
5、使用MultiBinding