最近在学习WPF,通过看书,敲代码和做笔记等各种方式.昨天学习完了Binding这一章... ... 画了张图进行总结,以备遗忘时查看.
1.Binding数据的校验
public _02Binding_ValidationRules() { InitializeComponent(); Binding binding = new Binding("Value") { Source = slider1, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }; RangeValidationRule rvr = new RangeValidationRule(); rvr.ValidatesOnTargetUpdated = true; binding.ValidationRules.Add(rvr); binding.NotifyOnValidationError = true; textBox1.SetBinding(TextBox.TextProperty, binding); this.textBox1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(ValidationError)); //this.slider1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(ValidationError2)); } void ValidationError(Object sender, RoutedEventArgs e) { if (Validation.GetErrors(this.textBox1).Count > 0) { textBox1.ToolTip = Validation.GetErrors(this.textBox1)[0].ErrorContent.ToString(); } } public class RangeValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { double d; if (double.TryParse(value.ToString(), out d)) { if (d >= 0 && d <= 100) { return new ValidationResult(true, null); } } return new ValidationResult(false, "验证失败!"); } }
2.Binding的数据转换
(效果图)
C# /// <summary> /// 种类 /// </summary> public enum Category { Bomber, Fighter } /// <summary> /// 状态 /// </summary> public enum State { Available, Locked, Unknown } /// <summary> /// 飞机类 /// </summary> public class Plane { public string Name { get; set; } public Category Category { get; set; } public State State { get; set; } } C# 窗体.cs /// <summary> /// 给ListBox的ItemsSource属性赋值 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonLoad_Click(object sender, RoutedEventArgs e) { ObservableCollection<Plane> planeList = new ObservableCollection<Plane>() { new Plane(){Category=Category.Bomber,Name="B-1",State=State.Unknown}, new Plane(){Category=Category.Bomber,Name="B-2",State=State.Unknown}, new Plane(){Category=Category.Fighter,Name="F-22",State=State.Unknown}, new Plane(){Category=Category.Fighter,Name="Su-47",State=State.Unknown}, new Plane(){Category=Category.Bomber,Name="B-52",State=State.Unknown}, new Plane(){Category=Category.Fighter,Name="J-10",State=State.Unknown}, }; this.listBoxPlane.ItemsSource=planeList; } private void buttonSave_Click(object sender, RoutedEventArgs e) { StringBuilder sb = new StringBuilder(); foreach (Plane p in listBoxPlane.Items) { sb.AppendLine(string.Format("Category={0},Name={1},State={2}",p.Category,p.Name,p.State)); } File.WriteAllText(@"D:\PlaneList.txt",sb.ToString()); MessageBox.Show("OK"); }
C# 转换类 需要IValueConverter接口
Convert函数为源到目标时调用
ConvertBack函数为目标到源时调用
public class CategoryToSourceConverter : IValueConverter { //将Category转换为Uri public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Category c = (Category)value; switch (c) { case Category.Bomber: return @"Icons\Bomber.png"; case Category.Fighter: return @"Icons\Fighter.png"; default: return null; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } public class StateToNullabelBoolConverter : IValueConverter { /// <summary> ///将State转换为Bool /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { State s = (State)value; switch (s) { case State.Available: return true; case State.Locked: return false; case State.Unknown: default: return null; } } /// <summary> /// 将Bool转换为State /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { bool? nb = (bool?)value; switch (nb) { case true: return State.Available; case false: return State.Locked; case null: default: return State.Unknown; } } } Xaml <Window.Resources> <local:CategoryToSourceConverter x:Key="cts"/> <local:StateToNullabelBoolConverter x:Key="stnb"/> </Window.Resources> <StackPanel Background="LightBlue"> <ListBox x:Name="listBoxPlane" Height="160" Margin="5"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <Image Width="20" Height="20" Source="{Binding Path=Category,Converter={StaticResource cts}}"/> <TextBlock Text="{Binding Path=Name}" Width=" 60" Margin="8,0"/> <CheckBox IsThreeState="true" IsChecked="{Binding Path=State,Converter={StaticResource stnb}}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <Button x:Name="buttonLoad" Content="Load" Height="25" Margin="5" Click="buttonLoad_Click"/> <Button x:Name="buttonSave" Content="Save" Height="25" Margin="5,5" Click="buttonSave_Click"/> </StackPanel>
3.MultiBinding(多路Binding)
C# namespace MyTestWPFApplication._2015年9月16日 { /// <summary> /// _04MultiBinding.xaml 的交互逻辑 /// </summary> public partial class _04MultiBinding : Window { public _04MultiBinding() { InitializeComponent(); SetMultiBinding(); } void SetMultiBinding() { Binding b1 = new Binding("Text") { Source = textBox1 }; Binding b2 = new Binding("Text") { Source = textBox2 }; Binding b3 = new Binding("Text") { Source = textBox3 }; Binding b4 = new Binding("Text") { Source = textBox4 }; MultiBinding mb = new MultiBinding() { Mode = BindingMode.OneWay }; mb.Bindings.Add(b1); mb.Bindings.Add(b2); mb.Bindings.Add(b3); mb.Bindings.Add(b4); mb.Converter = new LogonMultiBindingConverter(); button1.SetBinding(Button.IsEnabledProperty, mb); } } //因为这里的Converter类是是用来给MultiBinding的Converter来指定的.所以继承的接口不再是IValueConverter而是IMultiValueConverter class LogonMultiBindingConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (!values.Cast<string>().Any(text => string.IsNullOrEmpty(text)) && values[0].ToString() == values[1].ToString() && values[2].ToString() == values[3].ToString()) { return true; } return false; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } XAML <StackPanel Background="LightBlue"> <TextBox x:Name="textBox1" Height="23" Margin="5,25,5,5" Width="140"/> <TextBox x:Name="textBox2" Height="23" Margin="5" Width="140"/> <TextBox x:Name="textBox3" Height="23" Margin="5" Width="140"/> <TextBox x:Name="textBox4" Height="23" Margin="5" Width="140"/> <Button x:Name="button1" Content="Submit" Width="80" Margin="5"></Button> </StackPanel>
Binding学完了!
时间: 2024-11-09 17:11:50