关于动态字符串的绑定
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
本文作者:孤沉
本文链接:https://www.cnblogs.com/guchen33/p/18060276
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2023-03-08 Prism报错