none
WPF中XML件中的Textbox.txt如何数据绑定到Person类的实例 Zhang.name RRS feed

  • 问题

  • XAML 文件内容
    <Window x:Class="myWPF.MainWindow" Name="MainWindow1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="myWPF" Height="544" Width="850" >
    <Grid>
    <TextBox />
      </Grid>      
    </Window>

    MainWindow.cs文件内容

    namespace myWPF
    {
      public partial class MainWindow : Window
      {
         private Person Zhang = new Person("Zhang");
     }
    }

    就是想让Textbox.txt 和 实例 Zhang 的属性数据绑定。

    请问在XAML  文件中如何实现~!

    2011年4月1日 11:36

答案

  • 我想了下,好像对于XAML 和CLR中的对象实例进行绑定最好全部在XAML中完成,这样对于代码分离来说是有益处的。外观的事就让XAML去干,数据逻辑的事交给cs文件。但是这样cs代码不是一般的长啊

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.ComponentModel;
    using System.Globalization;
    
    namespace BindingWPF
    { 
     public partial class MainWindow : Window
     {
     private Person Person; 
     public MainWindow()
     {
      InitializeComponent();
      UIdataBinding();
      
     }
    
     private void UIdataBinding()
     {
      Person = new Person("zhang",18,new DateTime(2008, 5, 1, 8, 30, 52));
      //this.DataContext = this.Person;
      BindText(this.textBox1, Person.Name); // this.textBox1 绑定Name,好像没有成功??
      // this.textBox2 绑定Age
      // this.textBox2 绑定 BirthDay
      // 需要双向绑定
     }
    
     static void BindText(TextBox textBox, string property)
     {
      DependencyProperty textProp = TextBox.TextProperty;
      if (!BindingOperations.IsDataBound(textBox, textProp))
      {
      Binding b = new Binding(property);
      b.Mode = BindingMode.TwoWay;
      BindingOperations.SetBinding(textBox, textProp, b);
      }
     } 
     
    
     }
     public class Person :INotifyPropertyChanged
    
     {
     private string name;
     private UInt16 age;
     private DateTime birthDay; 
     public event PropertyChangedEventHandler PropertyChanged;
     public string Name
     {  
      get{return this.name;}
      set{
      this.name=value;
      OnPropertyChanged("PersonName");
      }
     }
     public UInt16 Age
     {
      get { return this.age; }
      set
      {
      this.age = value;
      OnPropertyChanged("PersonAge");
      }
     }
     public DateTime
    { get { return this.birthDay; } set { this.birthDay = value; OnPropertyChanged("PersonBirthDay"); } } public Person(string Name, UInt16 Age, DateTime BirthDay) { this.Name = Name; this.Age = Age; this.BirthDay = BirthDay; } protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } /// <summary>DateTime类和String类的数据转换</summary> [ValueConversion(typeof(DateTime), typeof(String))] public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { DateTime date = (DateTime)value; return date.ToShortDateString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string strValue = value as string; DateTime resultDateTime; if (DateTime.TryParse(strValue, out resultDateTime)) { return resultDateTime; } return DependencyProperty.UnsetValue; } } }

    这里没有this.DataContext = this 还是不行.. 

    我不明白LZ为什么不想赋值DataContext .. 还是如果用ElementName, LZ接受不..

    这里Person估计得定义成DependencyProperty..  不然Pserson赋值后没法通知

    <Window x:Class="BindingWPF.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
      Title="MainWindow" Height="350" Width="525"
      x:Name="m_self">
     
     <Grid>
      <TextBox Height="23" HorizontalAlignment="Left" Margin="217,45,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Person.Name}" />
      <!--设置数据绑定-->
      <TextBox Height="23" HorizontalAlignment="Left" Margin="217,93,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" Text="{Binding Person.Age, ElementName=m_self, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
      <TextBox Height="24" HorizontalAlignment="Left" Margin="217,145,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" Text="{Binding Person.Birthday, ElementName=m_self, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
      <Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="123,43,0,0" Name="Label1" VerticalAlignment="Top" />
     </Grid>
    </Window>
    

     


    just another day.
    2011年4月2日 11:57
  • public partial class Window2 : Window
      {
        public Person Person;
        public Window2()
        {
          InitializeComponent();
          Person = new Person("zhang", 18, new DateTime(2008, 5, 1, 8, 30, 52));
          UIdataBinding();
        }
        private void UIdataBinding()
        {
          this.DataContext = this.Person;
          BindText(this.textBox1, "Name"); // this.textBox1 绑定Name,好像没有成功??
          BindText(this.textBox2, "Age");
          BindText(this.textBox3, "BirthDay", new DateConverter());
        }
    
        static void BindText(TextBox textBox, string property)
        {
          BindText(textBox, property, null);
        }
    
        static void BindText(TextBox textBox, string property, IValueConverter valueConverter)
        {
          DependencyProperty textProp = TextBox.TextProperty;
          if (!BindingOperations.IsDataBound(textBox, textProp))
          {
            Binding b = new Binding(property);
            b.Mode = BindingMode.TwoWay;
            b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    
            if (null != valueConverter)
            {
              b.Converter = valueConverter;
            }
    
            BindingOperations.SetBinding(textBox, textProp, b);
          }
        }
      }
    
    这段代码测试过...可行..
    不过我觉得Binding操作还是直接在xaml里写比较好..

    just another day.
    2011年4月3日 2:50
  • 教你一种怎么在XAML里面写DataContext和直接绑定的方法:

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
     <StackPanel>
      <StackPanel.DataContext>
       <local:Person Name="Bob" Age="25">
        <local:Person.BirthDay>
         <sys:DateTime>1986/7/16</sys:DateTime>
        </local:Person.BirthDay>
       </local:Person>
      </StackPanel.DataContext>
      <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/>
      <TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"/>
      <TextBox>
       <TextBox.Text>
        <Binding Path="BirthDay" UpdateSourceTrigger="PropertyChanged">
         <Binding.Converter>
          <local:DateConverter />
         </Binding.Converter>
        </Binding>
       </TextBox.Text>
      </TextBox>
      <Button Content="Show data" Margin="5" Click="Button_Click"/>
     </StackPanel>
    </Window>
    
    

     

    完整例子:http://cid-51b2fdd068799d15.office.live.com/self.aspx/.Public/Samples%5E_2011/20110403%5E_BindingAllInXAML.zip


    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年4月3日 6:28
    版主
  • 恩 在XAML中可以比较轻松的绑定了。

    我想的是XAML中仅提供UI布局,数据绑定完全在cs文件中完成 ?

    this.DataContext = this.Person;
                BindText(this.textBox1, "Name"); // 绑定Name成功
    这个代码可以让绑定成功。

    请问该如何实现!~!

     this.DataContext = this.Person;

    是不是每进行一个不同的类实例绑定时都要声明。

    这个语句该如何写到
    static void BindText(TextBox textBox, string property)
    方法中去,就是说绑定完全在

    BindText()方法中实现

    2011年4月3日 14:34
  •  static void BindText(TextBox textBox,object obj ,string property)
    
     {
    
      DependencyProperty textProp = TextBox.TextProperty;
    
      if (!BindingOperations.IsDataBound(textBox, textProp))
    
      {
    
      textBox.DataContext = obj;
    
      Binding b = new Binding(property);
    
      b.Mode = BindingMode.TwoWay;
    
      b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    
      BindingOperations.SetBinding(textBox, textProp, b);  
    
      }
    
     } 
                BindText(this.textBox1, "Name"); // 绑定Name成功
                Person.Name = "Li"; // 为什么没有更新?
    2011年4月3日 14:53

全部回复

  • this.DataContext = this;

    <TextBox text = {binding path = Name}/>

    没测试,有问题告诉我。


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.


    2011年4月1日 12:02
    版主
  • 哈哈,拆个台,楼主的代码有问题,

    绑定的数据源应该是一个CLR属性才行,所以代码应该是:

    namespace myWPF
    {
      public partial class MainWindow : Window
      {
         public Person Zhang {get; set;}

         public MainWindow()
         {
           InitializeComponent();
           Zhang = new Person("Zhang");
           this.DataContext = this;
         }
      }

      public class Person
      {
         public string Name {get; set;}

         public Person(string name)
         {
            Name = name;
         }
      }
    }

     

    XAML: 如楼上

    <TextBox Text = {Binding Path = Zhang.Name}/>

     


    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年4月1日 15:39
    版主
  • 我测试了下 好像有问题

    namespace BindingWPF
    { 
      public partial class MainWindow : Window
      {
        private Person Person;  
        public MainWindow()
        {
          InitializeComponent();
          Person = new Person("zhang");
          this.DataContext = this;
        }
      }
      public class Person :INotifyPropertyChanged
    
      {
        private string name;
        public event PropertyChangedEventHandler PropertyChanged;
        public string Name
        {      
          get{return this.name;}
          set{
            this.name=value;
            OnPropertyChanged("PersonName");
            }
        } 
       
        public Person(string Name)
        {
          this.name = Name;
        }
        protected void OnPropertyChanged(string name)
        {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
            handler(this, new PropertyChangedEventArgs(name));
          }
        }
    
      }
    }

     

    <Window x:Class="BindingWPF.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     
            Title="MainWindow" Height="350" Width="525">
     
        <Grid>
            <TextBox Height="23" HorizontalAlignment="Left" Margin="217,45,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding}" />
            <!--设置数据绑定-->
            <TextBox Height="23" HorizontalAlignment="Left" Margin="217,93,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
            <TextBox Height="24" HorizontalAlignment="Left" Margin="217,145,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" />
            <Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="123,43,0,0" Name="Label1" VerticalAlignment="Top" />
        </Grid>
    </Window>

    是不是XML中还需要名称空间的引用?好像 Person和XML的MainWindow是同一个名称空间啊 !~

    2011年4月1日 16:39
  • this.DataContext = person;

    xaml: text = {binding Name}

     


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年4月1日 16:45
    版主
  •     

       this.DataContext = this.Person;

    <TextBox Height="23" HorizontalAlignment="Left" Margin="217,45,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Name}" />


    Best day, Best life
    2011年4月1日 16:46
  • 。。。 好像我快点~ 因为我没开VS


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年4月1日 16:47
    版主
  • 恩 在cs代码中  this.DataContext = this.Person;

    在xaml代码中 Text="{Binding Name}" 是可行的

    但是如果想在cs代码中 不写 //this.DataContext = this.Person;

    namespace BindingWPF
    {
      public partial class MainWindow : Window
      {
        private Person Person; 
        public MainWindow()
        {
          InitializeComponent();
          Person = new Person("zhang");
         // this.DataContext = this.Person;  

      }
      }

    ....

    ...

    }

    就是说 完全在xaml代码中实现数据绑定到 Person.Name如何做到?

    2011年4月1日 18:10
  • 我想了下,好像对于XAML 和CLR中的对象实例进行绑定最好全部在XAML中完成,这样对于代码分离来说是有益处的。外观的事就让XAML去干,数据逻辑的事交给cs文件。但是这样cs代码不是一般的长啊

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.ComponentModel;
    using System.Globalization;
    
    namespace BindingWPF
    { 
      public partial class MainWindow : Window
      {
        private Person Person;  
        public MainWindow()
        {
          InitializeComponent();
          UIdataBinding();
          
        }
    
        private void UIdataBinding()
        {
          Person = new Person("zhang",18,new DateTime(2008, 5, 1, 8, 30, 52));
          //this.DataContext = this.Person;
          BindText(this.textBox1, Person.Name); // this.textBox1 绑定Name,好像没有成功??
          // this.textBox2 绑定Age
          // this.textBox2 绑定 BirthDay
          // 需要双向绑定
        }
    
        static void BindText(TextBox textBox, string property)
        {
          DependencyProperty textProp = TextBox.TextProperty;
          if (!BindingOperations.IsDataBound(textBox, textProp))
          {
            Binding b = new Binding(property);
            b.Mode = BindingMode.TwoWay;
            BindingOperations.SetBinding(textBox, textProp, b);
          }
        }    
        
    
      }
      public class Person :INotifyPropertyChanged
    
      {
        private string name;
        private UInt16 age;
        private DateTime birthDay;    
        public event PropertyChangedEventHandler PropertyChanged;
        public string Name
        {      
          get{return this.name;}
          set{
            this.name=value;
            OnPropertyChanged("PersonName");
            }
        }
        public UInt16 Age
        {
          get { return this.age; }
          set
          {
            this.age = value;
            OnPropertyChanged("PersonAge");
          }
        }
        public DateTime BirthDay
        {
          get { return this.birthDay; }
          set
          {
            this.birthDay = value;
            OnPropertyChanged("PersonBirthDay");
          }
        }
        public Person(string Name, UInt16 Age, DateTime BirthDay)
        {
          this.Name = Name;
          this.Age = Age;
          this.BirthDay = BirthDay;
        }
        protected void OnPropertyChanged(string name)
        {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
            handler(this, new PropertyChangedEventArgs(name));
          }
        }
    
      }
    
      /// <summary>DateTime类和String类的数据转换</summary>    
      [ValueConversion(typeof(DateTime), typeof(String))]
      public class DateConverter : IValueConverter
      {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
          DateTime date = (DateTime)value;
          return date.ToShortDateString();
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
          string strValue = value as string;
          DateTime resultDateTime;
          if (DateTime.TryParse(strValue, out resultDateTime))
          {
            return resultDateTime;
          }
          return DependencyProperty.UnsetValue;
        }
      }
    
    
    }
    
    2011年4月2日 2:18
  • 我测试了下 好像有问题

    namespace BindingWPF
    { 
     public partial class MainWindow : Window
     {
      private Person Person; 
      public MainWindow()
      {
       InitializeComponent();
       Person = new Person("zhang");
       this.DataContext = this;
      }
     }
     public class Person :INotifyPropertyChanged
    
     {
      private string name;
      public event PropertyChangedEventHandler PropertyChanged;
      public string Name
      {   
       get{return this.name;}
       set{
        this.name=value;
        OnPropertyChanged("PersonName");
        }
      } 
      
      public Person(string Name)
      {
       this.name = Name;
      }
      protected void OnPropertyChanged(string name)
      {
       PropertyChangedEventHandler handler = PropertyChanged;
       if (handler != null)
       {
        handler(this, new PropertyChangedEventArgs(name));
       }
      }
    
     }
    }

     

    <Window x:Class="BindingWPF.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     
            Title="MainWindow" Height="350" Width="525">
     
        <Grid>
            <TextBox Height="23" HorizontalAlignment="Left" Margin="217,45,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding}" />
            <!--设置数据绑定-->
            <TextBox Height="23" HorizontalAlignment="Left" Margin="217,93,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
            <TextBox Height="24" HorizontalAlignment="Left" Margin="217,145,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" />
            <Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="123,43,0,0" Name="Label1" VerticalAlignment="Top" />
        </Grid>
    </Window>

    是不是XML中还需要名称空间的引用?好像 Person和XML的MainWindow是同一个名称空间啊 !~

    这个不行是因为Person是Private的 ..而且Binding那里Path应该是Person.Name
    just another day.
    2011年4月2日 11:39
  • 我想了下,好像对于XAML 和CLR中的对象实例进行绑定最好全部在XAML中完成,这样对于代码分离来说是有益处的。外观的事就让XAML去干,数据逻辑的事交给cs文件。但是这样cs代码不是一般的长啊

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.ComponentModel;
    using System.Globalization;
    
    namespace BindingWPF
    { 
     public partial class MainWindow : Window
     {
     private Person Person; 
     public MainWindow()
     {
      InitializeComponent();
      UIdataBinding();
      
     }
    
     private void UIdataBinding()
     {
      Person = new Person("zhang",18,new DateTime(2008, 5, 1, 8, 30, 52));
      //this.DataContext = this.Person;
      BindText(this.textBox1, Person.Name); // this.textBox1 绑定Name,好像没有成功??
      // this.textBox2 绑定Age
      // this.textBox2 绑定 BirthDay
      // 需要双向绑定
     }
    
     static void BindText(TextBox textBox, string property)
     {
      DependencyProperty textProp = TextBox.TextProperty;
      if (!BindingOperations.IsDataBound(textBox, textProp))
      {
      Binding b = new Binding(property);
      b.Mode = BindingMode.TwoWay;
      BindingOperations.SetBinding(textBox, textProp, b);
      }
     } 
     
    
     }
     public class Person :INotifyPropertyChanged
    
     {
     private string name;
     private UInt16 age;
     private DateTime birthDay; 
     public event PropertyChangedEventHandler PropertyChanged;
     public string Name
     {  
      get{return this.name;}
      set{
      this.name=value;
      OnPropertyChanged("PersonName");
      }
     }
     public UInt16 Age
     {
      get { return this.age; }
      set
      {
      this.age = value;
      OnPropertyChanged("PersonAge");
      }
     }
     public DateTime
    { get { return this.birthDay; } set { this.birthDay = value; OnPropertyChanged("PersonBirthDay"); } } public Person(string Name, UInt16 Age, DateTime BirthDay) { this.Name = Name; this.Age = Age; this.BirthDay = BirthDay; } protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } /// <summary>DateTime类和String类的数据转换</summary> [ValueConversion(typeof(DateTime), typeof(String))] public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { DateTime date = (DateTime)value; return date.ToShortDateString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string strValue = value as string; DateTime resultDateTime; if (DateTime.TryParse(strValue, out resultDateTime)) { return resultDateTime; } return DependencyProperty.UnsetValue; } } }

    这里没有this.DataContext = this 还是不行.. 

    我不明白LZ为什么不想赋值DataContext .. 还是如果用ElementName, LZ接受不..

    这里Person估计得定义成DependencyProperty..  不然Pserson赋值后没法通知

    <Window x:Class="BindingWPF.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
      Title="MainWindow" Height="350" Width="525"
      x:Name="m_self">
     
     <Grid>
      <TextBox Height="23" HorizontalAlignment="Left" Margin="217,45,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Person.Name}" />
      <!--设置数据绑定-->
      <TextBox Height="23" HorizontalAlignment="Left" Margin="217,93,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" Text="{Binding Person.Age, ElementName=m_self, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
      <TextBox Height="24" HorizontalAlignment="Left" Margin="217,145,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" Text="{Binding Person.Birthday, ElementName=m_self, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
      <Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="123,43,0,0" Name="Label1" VerticalAlignment="Top" />
     </Grid>
    </Window>
    

     


    just another day.
    2011年4月2日 11:57
  • 这个问题的实现是通过两步

    在cs代码中  this.DataContext = this.Person;

    在xaml代码中 Text="{Binding Name}"

    那么这个问题的解还有有两种可能

    1、完全在xaml文件中实现

    2、完全在cs文件中实现

    我更倾向于后一种。即UI和数据逻辑分离。那么问题就变成了下面~~

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.ComponentModel;
    using System.Globalization;
    
    namespace BindingWPF
    { 
     public partial class MainWindow : Window
     {
      private Person Person; 
      public MainWindow()
      {
       InitializeComponent();   
       Person = new Person("zhang", 18, new DateTime(2008, 5, 1, 8, 30, 52));
       UIdataBinding();   
      }
      private void UIdataBinding()
      {   
       //this.DataContext = this.Person;
       BindText(this.textBox1, Person.Name); // this.textBox1 绑定Name,好像没有成功??
       // this.textBox2 绑定Age
       // this.textBox2 绑定 BirthDay
       // 需要双向绑定
      }
    
      static void BindText(TextBox textBox, string property)
      {
       DependencyProperty textProp = TextBox.TextProperty;
       if (!BindingOperations.IsDataBound(textBox, textProp))
       {
        Binding b = new Binding(property);
        b.Mode = BindingMode.TwoWay;
        BindingOperations.SetBinding(textBox, textProp, b);    
       }
      }  
      
    
     }
     public class Person :INotifyPropertyChanged
    
     {
      private string name;
      private UInt16 age;
      private DateTime birthDay;  
      public event PropertyChangedEventHandler PropertyChanged;
      public string Name
      {   
       get{return this.name;}
       set{
        this.name=value;
        OnPropertyChanged("PersonName");
        }
      }
      public UInt16 Age
      {
       get { return this.age; }
       set
       {
        this.age = value;
        OnPropertyChanged("PersonAge");
       }
      }
      public DateTime BirthDay
      {
       get { return this.birthDay; }
       set
       {
        this.birthDay = value;
        OnPropertyChanged("PersonBirthDay");
       }
      }  
      public Person(string Name, UInt16 Age, DateTime BirthDay)
      {
       this.Name = Name;
       this.Age = Age;
       this.BirthDay = BirthDay;
      }
      protected void OnPropertyChanged(string name)
      {
       PropertyChangedEventHandler handler = PropertyChanged;
       if (handler != null)
       {
        handler(this, new PropertyChangedEventArgs(name));
       }
      }
    
     }
    
     /// <summary>DateTime类和String类的数据转换</summary>  
     [ValueConversion(typeof(DateTime), typeof(String))]
     public class DateConverter : IValueConverter
     {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
       DateTime date = (DateTime)value;
       return date.ToShortDateString();
      }
    
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
       string strValue = value as string;
       DateTime resultDateTime;
       if (DateTime.TryParse(strValue, out resultDateTime))
       {
        return resultDateTime;
       }
       return DependencyProperty.UnsetValue;
      }
     }
    
    
    }
    上面如何实现数据绑定?
    2011年4月2日 14:49
  • 恩 是的
    2011年4月2日 14:50
  • public partial class Window2 : Window
      {
        public Person Person;
        public Window2()
        {
          InitializeComponent();
          Person = new Person("zhang", 18, new DateTime(2008, 5, 1, 8, 30, 52));
          UIdataBinding();
        }
        private void UIdataBinding()
        {
          this.DataContext = this.Person;
          BindText(this.textBox1, "Name"); // this.textBox1 绑定Name,好像没有成功??
          BindText(this.textBox2, "Age");
          BindText(this.textBox3, "BirthDay", new DateConverter());
        }
    
        static void BindText(TextBox textBox, string property)
        {
          BindText(textBox, property, null);
        }
    
        static void BindText(TextBox textBox, string property, IValueConverter valueConverter)
        {
          DependencyProperty textProp = TextBox.TextProperty;
          if (!BindingOperations.IsDataBound(textBox, textProp))
          {
            Binding b = new Binding(property);
            b.Mode = BindingMode.TwoWay;
            b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    
            if (null != valueConverter)
            {
              b.Converter = valueConverter;
            }
    
            BindingOperations.SetBinding(textBox, textProp, b);
          }
        }
      }
    
    这段代码测试过...可行..
    不过我觉得Binding操作还是直接在xaml里写比较好..

    just another day.
    2011年4月3日 2:50
  • 教你一种怎么在XAML里面写DataContext和直接绑定的方法:

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
     <StackPanel>
      <StackPanel.DataContext>
       <local:Person Name="Bob" Age="25">
        <local:Person.BirthDay>
         <sys:DateTime>1986/7/16</sys:DateTime>
        </local:Person.BirthDay>
       </local:Person>
      </StackPanel.DataContext>
      <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/>
      <TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"/>
      <TextBox>
       <TextBox.Text>
        <Binding Path="BirthDay" UpdateSourceTrigger="PropertyChanged">
         <Binding.Converter>
          <local:DateConverter />
         </Binding.Converter>
        </Binding>
       </TextBox.Text>
      </TextBox>
      <Button Content="Show data" Margin="5" Click="Button_Click"/>
     </StackPanel>
    </Window>
    
    

     

    完整例子:http://cid-51b2fdd068799d15.office.live.com/self.aspx/.Public/Samples%5E_2011/20110403%5E_BindingAllInXAML.zip


    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年4月3日 6:28
    版主
  • 恩  是的

                this.DataContext = this.Person;
                BindText(this.textBox1, "Name"); // 绑定Name成功
                Person.Name = "Li"; // 为什么没有更新?

    2011年4月3日 14:31
  • 恩 在XAML中可以比较轻松的绑定了。

    我想的是XAML中仅提供UI布局,数据绑定完全在cs文件中完成 ?

    this.DataContext = this.Person;
                BindText(this.textBox1, "Name"); // 绑定Name成功
    这个代码可以让绑定成功。

    请问该如何实现!~!

     this.DataContext = this.Person;

    是不是每进行一个不同的类实例绑定时都要声明。

    这个语句该如何写到
    static void BindText(TextBox textBox, string property)
    方法中去,就是说绑定完全在

    BindText()方法中实现

    2011年4月3日 14:34
  •  static void BindText(TextBox textBox,object obj ,string property)
    
     {
    
      DependencyProperty textProp = TextBox.TextProperty;
    
      if (!BindingOperations.IsDataBound(textBox, textProp))
    
      {
    
      textBox.DataContext = obj;
    
      Binding b = new Binding(property);
    
      b.Mode = BindingMode.TwoWay;
    
      b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    
      BindingOperations.SetBinding(textBox, textProp, b);  
    
      }
    
     } 
                BindText(this.textBox1, "Name"); // 绑定Name成功
                Person.Name = "Li"; // 为什么没有更新?
    2011年4月3日 14:53
  • 恩  是的

                this.DataContext = this.Person;
                BindText(this.textBox1, "Name"); // 绑定Name成功
                Person.Name = "Li"; // 为什么没有更新?

     public string Name
     {  
      get{return this.name;}
      set{
      this.name=value;
      OnPropertyChanged("PersonName");
      }
     }
    因为这里OnPropertyChanged给的参数不对.. 这个必须跟属性名一致..也就是Name

    just another day.
    2011年4月3日 14:59
  • OnPropertyChanged("PersonName");
    这个改为OnPropertyChanged("Name");就好了

    2011年4月3日 15:06
  • 恩 在XAML中可以比较轻松的绑定了。

    我想的是XAML中仅提供UI布局,数据绑定完全在cs文件中完成 ?

    this.DataContext = this.Person;
                BindText(this.textBox1, "Name"); // 绑定Name成功
    这个代码可以让绑定成功。

    请问该如何实现!~!

     this.DataContext = this.Person;

    是不是每进行一个不同的类实例绑定时都要声明。

    这个语句该如何写到
    static void BindText(TextBox textBox, string property)
    方法中去,就是说绑定完全在

    BindText()方法中实现

    如果你有一个新类比如Country . 你再设置this.DataContext = this.Country 那么原来Person的Source就丢失了

    其实如果不是自定义控件里面的属性. 一般会定义一个ViewModel,将ViewModel赋值为DataContext.  Xaml里使用Binding也不会影响你布局.. 而且ViewModel里的数据就是你UI的数据..后面有什么逻辑可以直接针对ViewModel操作.

    不知道你有没有了解过Prism   这个值得看看..


    just another day.
    2011年4月3日 15:07
  • 恩 主要是想 UI完全和逻辑分离,xaml完全当UI元素的画布。

    2011年4月3日 15:09
  • 试试接触MVVM模式  那才是真正的UI 与 逻辑分离
    Best day, Best life
    2011年4月3日 18:19