WPF绑定并转换
首先新建个项目,我的项目名叫BindConverterDemo,你的话什么都可以,我这里只是做demo
再建两个类,DataDemo,ConverterDemo
这个是DataDemo类
public class DataDemo:INotifyPropertyChanged { private DateTime dateTime; public DataDemo() { dateTime = DateTime.Now; } public DateTime TheDateTime { get { return dateTime; } set { dateTime = value; } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string info) { PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(info)); } }
public class ConverterDemo : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var date = (DateTime)value; switch (targetType.Name) { case "String": return date.ToString("F",culture); case "Brush": return Brushes.Blue; default: return value; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } }
再来处理界面XAMl代码,如下代码所示
<StackPanel> <StackPanel.Resources> <local:DataDemo x:Key="DataDemos"/> <local:ConverterDemo x:Key="ConverterDemos"/> <Style TargetType="TextBlock"> <Setter Property="FontSize" Value="24"/> <Setter Property="Margin" Value="5"/> </Style> </StackPanel.Resources> <StackPanel.DataContext> <Binding Source="{StaticResource DataDemos}"/> </StackPanel.DataContext> <TextBlock Text="为转换的数据:"/> <TextBlock Text="{Binding Path=TheDateTime}"/> <TextBlock Text="转换的数据:"/> <TextBlock Foreground="{Binding Path=TheDateTime,Converter={StaticResource ConverterDemos}}"> <TextBlock.Text> <Binding Path="TheDateTime" Converter="{StaticResource ConverterDemos}"/> </TextBlock.Text> </TextBlock> </StackPanel>
然后看看运行的效果如何
谢谢,欣赏!本博客只用于学习用途。
多看书,少装逼!