Binding

作者: 落地成佛 | 来源:发表于2019-07-23 13:43 被阅读0次

    一、概述

    二、使用

    2.1 前端绑定方法

    
    <TextBox x:Name="textBox1"  Text="{Binding Path=Value,ElementName=slider1}"/>
    //等价于
    <TextBox x:Name="textBox1"  Text="{Binding Value,ElementName=slider1}"/>
    textBox1.SetBinding(TextBox.TextProperty,new Binding() {Path=new PropertyPath("Value") ,ElementName= "slider1"})
    textBox1.SetBinding(TextBox.TextProperty,new Binding("Value") { ElementName= "slider1"})
    textBox1.SetBinding(TextBox.TextProperty,new Binding("Value") { Source= slider1})
    

    2.2 INotifyPropertyChanged

    //绑定类实现INotifyPropertyChanged接口,属性需要动态绑定的进行注册(PropertyChanged)
     public class Student : INotifyPropertyChanged
        {
            private string name;
    
            public string Name
            {
                get { return name; }
                set
                {
                    name = value;
                    if (PropertyChanged != null)
                    {
                        this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
                    }
                }
            }
            public event PropertyChangedEventHandler PropertyChanged;
        }
    
    //确定绑定对象及具体的绑定属性
    //确定绑定控件及具体的绑定控件属性
    stu = new WpfApplication1.Model.Student();
    
    Binding binding = new Binding();
    binding.Path = new PropertyPath("Name");
    ///简化: Binding binding = new Binding("Name");
    binding.Source = stu;
    
    BindingOperations.SetBinding(this.textBoxName, TextBox.TextProperty, binding);
    //简化: textBoxName.SetBinding(TextBox.TextProperty, binding);
    //简化: textBoxName.SetBinding(TextBox.TextProperty,new Binding("Name") { Source= stu });
    

    2.3 绑定方向

    Text="{Binding Path=Value,ElementName=slider1,Mode=TwoWay}"
    

    2.4 绑定集合

    采用/来表示

                this.textBox1.SetBinding(TextBox.TextProperty, new Binding("/Name") { Source=infos});
                this.textBox2.SetBinding(TextBox.TextProperty, new Binding("/Provinces/Name") { Source = infos });
                this.textBox3.SetBinding(TextBox.TextProperty, new Binding("/Provinces/Citys/Name") { Source = infos });
    
         class City
        {
            public string Name { set; get; }
        }
    
        class Province
        {
            public string Name { set; get; }
            public List<City> Citys { set; get; }
        }
    
        class Contry
        {
            public string Name { set; get; }
            public List<Province> Provinces { get; set; }
        }
    

    2.5 集合数据源ItemSource

     <StackPanel Height="295" HorizontalAlignment="Left" Margin="10,10,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="427">
                <TextBlock Height="23" Name="textBlock1" Text="学员编号:" />
                <TextBox Height="23" Name="txtStudentId" Width="301" HorizontalAlignment="Left"/>
                <TextBlock Height="23" Name="textBlock2" Text="学员列表:" />
                <ListBox Height="156" Name="lbStudent" Width="305" HorizontalAlignment="Left">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Name="stackPanel2" Orientation="Horizontal">
                                <TextBlock  Text="{Binding Id}" Margin="5" Background="Beige"/>
                                <TextBlock Text="{Binding Name}" Margin="5"/>
                                <TextBlock  Text="{Binding Age}" Margin="5"/>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
                <Button Content="Button" Height="23" Name="button1" Width="75" HorizontalAlignment="Left" Click="button1_Click" />
            </StackPanel>
    
    //ObservableCollection集合类型自动实现INotifyPropertyChanged,INotifyCollectionChanged
    //能把集合的变化立即通知控件
      ObservableCollection<Student> infos = new ObservableCollection<Student>() { 
                new Student(){ Id=1, Age=11, Name="Tom"},
                new Student(){ Id=2, Age=12, Name="Darren"},
                new Student(){ Id=3, Age=13, Name="Jacky"},
                new Student(){ Id=4, Age=14, Name="Andy"}
                };
            public Window8()
            {
                InitializeComponent();
    
                
                this.lbStudent.ItemsSource = infos;
                
    
                this.txtStudentId.SetBinding(TextBox.TextProperty,new Binding("SelectedItem.Id"){ Source=lbStudent});
            }
    
            private void button1_Click(object sender, RoutedEventArgs e)
            {
                infos[1] = new Student() { Id = 2, Age = 12, Name = "sss" };
            }
    
    

    2.56省略Path

    资源是字符串时可省略Path

        <StackPanel Height="184" Name="stackPanel1" Width="288">
            <StackPanel.Resources>
                <String:String x:Key="myString">
                    xxxxxxx
                </String:String>
                
            </StackPanel.Resources>
            <TextBlock Height="23" Name="textBlock1" Text="{Binding Path=.,Source={StaticResource ResourceKey=myString}}" />
        </StackPanel>
    

    2.7 省略数据源DataContext

    没有数据源,则会向上查找DataContext匹配的属性,直到找到。

     <StackPanel Background="AliceBlue">
            <StackPanel.DataContext>
                <Stu:Student Id="1" Name="Darren" Age="10"></Stu:Student>
            </StackPanel.DataContext>
            <Grid>
                <StackPanel Height="283" HorizontalAlignment="Left" Margin="12,12,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="418">
                    <TextBox Height="23" Name="textBox1" Width="120" Margin="15" Text="{Binding Path=Id}"/>
                    <TextBox Height="23" Name="textBox2" Width="120" Margin="15" Text="{Binding Path=Name}"/>
                    <TextBox Height="23" Name="textBox3" Width="120" Margin="15" Text="{Binding Path=Age}"/>
                </StackPanel>
            </Grid>
        </StackPanel>
    

    2.8 数据源DataTable

     <StackPanel Height="279" Name="stackPanel1" Width="431">
            <ListView Height="247" Name="listView1" Width="376">
                <ListView.View>
                    <GridView>
                       
                            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" Width="60">
                                
                            </GridViewColumn>
                            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="60">
    
                            </GridViewColumn>
                            <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="60">
    
                            </GridViewColumn>
                            <GridViewColumn Header="Sex" DisplayMemberBinding="{Binding Sex}" Width="60">
    
                            </GridViewColumn>
                       
                    </GridView>
                </ListView.View>
            </ListView>
        </StackPanel>
    
      DataTable dtInfo = CreateDataTable();
                for (int i = 0; i < 10; i++)
                {
                    DataRow dr = dtInfo.NewRow();
                    dr[0] = i;
                    dr[1] = "猴王" + i;
                    dr[2] = i + 10;
                    dr[3] = "男";
                    dtInfo.Rows.Add(dr);
                }
    
                this.listView1.DataContext = dtInfo;
                this.listView1.SetBinding(ListView.ItemsSourceProperty, new Binding());
    

    2.9 数据源XML

    <StackPanel Width="409" Height="331" Background="LightBlue">
            <ListView Height="302" Name="listView1" Width="396">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="ID" DisplayMemberBinding="{Binding XPath=@id}" Width="80">
                            
                        </GridViewColumn>
                        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding XPath=Name}" Width="150">
    
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
        </StackPanel>
    
       XmlDataProvider dp = new XmlDataProvider();
                dp.Source = new Uri(@"d:\我的文档\visual studio 2010\Projects\WpfApplication2\WpfApplication1\StudentData.xml");
               // dp.Document = doc;
    
                dp.XPath = @"StudentList/Student";
                this.listView1.DataContext = dp;
                this.listView1.SetBinding(ListView.ItemsSourceProperty, new Binding());
    

    2.10 ObjectDataProvider

       ObjectDataProvider odp = new ObjectDataProvider();
                odp.ObjectInstance = new Caculate();
                odp.MethodName="Add";
                odp.MethodParameters.Add("100");
                odp.MethodParameters.Add("200");
                MessageBox.Show(odp.Data.ToString());
    

    2.11 RelativeSource

    RelativeSource 用于无明确数据源,根据UI相对位置确定数据源

     <Grid Background="Red" Margin="10" x:Name="gd1">
            <DockPanel x:Name="dp1" Margin="10" Background="Orange">
                <Grid Background="Yellow" Margin="10" x:Name="gd2">
                    <DockPanel Name="dp2" Margin="10" Background="LawnGreen">
                        <TextBox  Name="textBox1"  Margin="10" FontSize="24" Text="{Binding Path=Name, RelativeSource={RelativeSource Mode=Self}}"/>
                    </DockPanel>
                </Grid>
            </DockPanel>
        </Grid>
    
    image.png

    2.12 ValidationRule

     public class RangeValidationRule : ValidationRule
        {
    
            public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
            {
                double d = 0;
                if(double.TryParse(value.ToString(),out d))
                {
                    if(d>=0&&d<=100)
                    {
                        return new ValidationResult(true,null);
                    }
                }
                return new ValidationResult(false,"ErrorContent");
            }
        }
      public Window16()
            {
                InitializeComponent();
                Binding bind =new Binding("Value") { UpdateSourceTrigger= UpdateSourceTrigger.PropertyChanged,Source=slider1, Mode= BindingMode.TwoWay};
                ValidationRule rule = new RangeValidationRule();
                //默认绑定目标值变化时验证,如要验证数据源变化则设置ValidatesOnTargetUpdated 为true
                rule.ValidatesOnTargetUpdated = true;
                bind.ValidationRules.Add(rule);
                bind.NotifyOnValidationError = true;
                this.textBox1.SetBinding(TextBox.TextProperty, bind);
                this.textBox1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(ValidationError));
            }
    
            private void ValidationError(object sender, RoutedEventArgs e)
            {
                if (Validation.GetErrors(textBox1).Count > 0)
                {
                    this.textBox1.ToolTip = Validation.GetErrors(textBox1)[0].ErrorContent.ToString();
                }
                else
                {
                    this.textBox1.ToolTip = "";
                }
            }
    

    2.12 IValueConverter

     public class StateToNullableBoolConverter:IValueConverter
        {
    
            public object Convert(object value, Type targetType, object parameters, System.Globalization.CultureInfo culture)
            {
                State state = (State)value;
                switch (state)
                {
                    case State.Available:
                        return true;
                        
                    case State.Locked:
                        return false;
                    case State.Unknown:
                        
                    default:
                        return null;
                }
            }
    
            public object ConvertBack(object value, Type targetType, object parameters, System.Globalization.CultureInfo culture)
            {
                bool? nb = (bool?)value;
                switch (nb)
                {
                    case true:
                        return State.Available;
                    case false:
                        return State.Locked;
                    case null:
                    default:
                        return State.Unknown;
                        
                }
            }
        }
    
        <Window.Resources>
            <local:CategoryToSourceConverter x:Key="cts" />
            <local:StateToNullableBoolConverter x:Key="snb" />
        </Window.Resources>
        <StackPanel Name="stackPanel1" Background="AliceBlue" Margin="10">
            <ListBox  Name="listBox1" Height="160" Margin="5">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Height="16" Name="image1" Stretch="Fill" Width="16" Source="{Binding Path=category,Converter={StaticResource cts}}"/>
                            <TextBlock Height="23" Name="textBlock1" Text="{Binding name}" Margin="8,0" Width="80"/>
                            <CheckBox  Height="16" Name="checkBox1" IsChecked="{Binding Path=state,Converter={StaticResource snb}}" IsThreeState="True"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
    

    2.13 MultiBinding

     //准备基础Binding
                Binding bind1 = new Binding("Text") { Source=textBox1};
                Binding bind2 = new Binding("Text") { Source = textBox2 };
                Binding bind3 = new Binding("Text") { Source = textBox3 };
                Binding bind4 = new Binding("Text") { Source = textBox4 };
    
                //准备MultiBinding
                MultiBinding mb = new MultiBinding() { Mode= BindingMode.OneWay};
                mb.Bindings.Add(bind1);//注意,MultiBinding对子元素的顺序是很敏感的。
                mb.Bindings.Add(bind2);
                mb.Bindings.Add(bind3);
                mb.Bindings.Add(bind4);
                mb.Converter = new MultiBindingConverter();
                ///将Binding和MultyBinding关联
                this.btnSubmit.SetBinding(Button.IsEnabledProperty, mb);
    
        public class MultiBindingConverter: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[3].ToString()==values[2].ToString())
                {
                    return true;
                }
                return false;
            }
            /// <summary>
            /// 该方法不会被调用
            /// </summary>
            /// <param name="value"></param>
            /// <param name="targetTypes"></param>
            /// <param name="parameter"></param>
            /// <param name="culture"></param>
            /// <returns></returns>
            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    

    相关文章

      网友评论

        本文标题:Binding

        本文链接:https://www.haomeiwen.com/subject/avonkctx.html