class Student{ public string Name {get;set;} public string Age {get;set;}} using System.ComponentModel; class Student : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string name; public string Name { get { return name; } set { name = value; //激發(fā)事件 if (this.PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); } } } }Student stu = new Student();Binding binding = new Binding();binding.Source = stu;binding.Path = new PropertyPath("Name");
BindingOperations.SetBinding(this.textBoxName,TextBox.TextProperty,binding); public BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase binding) { return BindingOperations.SetBinding(this, dp, binding); }this.textBoxName.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = stu = new Student() }); <StackPanel> <TextBox x:Name="textBox1" Text="{Binding Path=Value,ElementName=slider1}" BorderBrush="Black" Margin="5"/> <Slider x:Name="slider1" Maximum="100" Minimum="0" Margin="5"/> </StackPanel><TextBox x:Name="textBox1" Text="{Binding Path=Value,ElementName=slider1}" BorderBrush="Black" Margin="5"/>this.textBox1.SetBinding(TextBox.TextProperty, new Binding("Value") { ElementName = "slider1" }); this.textBox1.SetBinding(TextBox.TextProperty, new Binding("Value") { ElementName = "slider1" , Mode = BindingMode.OneWay});View Code
Binding binding = new Binding(){Path=new PropertyPath("Value"),Source=this.slidr1}; public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } <StackPanel Background="LightBlue" > <StackPanel.DataContext> <local:Student Id="6" Age="29" Name="tim"/> </StackPanel.DataContext> <Grid > <StackPanel> <TextBox Text="{Binding Path=Id}" Margin="5"/> <TextBox Text="{Binding Path=Name}" Margin="5" /> <TextBox Text="{Binding Path=Age}" Margin="5"/> </StackPanel> </Grid> </StackPanel>xmlns:sys="clr-namespace:System;assembly=mscorlib"
<StackPanel Background="LightBlue" > <StackPanel.DataContext> <sys:String >Hello DataContext!</sys:String> </StackPanel.DataContext> <Grid > <StackPanel> <TextBlock Text="{Binding}" Margin=" 5"/> <TextBlock Text="{Binding .}" Margin=" 5"/> </StackPanel> </Grid></StackPanel>
<StackPanel x:Name="stackPanel" Background="LightBlue" > <TextBlock Text="Student ID:" FontWeight="Bold" Margin="5" /> <TextBox x:Name="textBoxId" Margin="5"/> <TextBlock Text="Student List:" FontWeight="Bold" Margin="5"/> <ListBox x:Name="listBoxStudents" Height=" 110" Margin=" 5" /> </StackPanel> List<Student> stuList = new List<Student>() { new Student() { Id=0,Name="Tim",Age=29}, new Student() { Id=1,Name="Tom",Age=28}, }; //為L(cháng)istBox設置Binding this.listBoxStudents.ItemsSource = stuList; this.listBoxStudents.DisplayMemberPath = "Name";
//為T(mén)extBox設置Binding Binding binding = new Binding("SelectedItem.Id") { Source = this.listBoxStudents }; this.textBoxId.SetBinding(TextBox.TextProperty, binding);

<StackPanel x:Name="stackPanel" Background="LightBlue" > <TextBlock Text="Student ID:" FontWeight="Bold" Margin="5" /> <TextBox x:Name="textBoxId" Margin="5"/> <TextBlock Text="Student List:" FontWeight="Bold" Margin="5"/> <ListBox x:Name="listBoxStudents" Height=" 110" Margin=" 5" > <ListBox.ItemTemplate > <DataTemplate > <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Path=Id}" Width="30" /> <TextBlock Text="{Binding Path=Name}" Width="60" /> <TextBlock Text="{Binding Path=Age}" Width="30" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox></StackPanel>List<Student> stuList = new List<Student>(){ new Student() { Id=0, Name="Tim", Age=29 }, new Student() { Id=1, Name="Tom", Age=28 },};this.listBoxStudents.ItemsSource = stuList;//this.listBoxStudents.DisplayMemberPath = "Name"; this.textBoxId.SetBinding(TextBox.TextProperty, new Binding("SelectedItem.Id"){Source = this.listBoxStudents});<StackPanel x:Name="stackPanel" Background="LightBlue" > <ListBox x:Name="listBoxStudents" Height=" 110" Margin=" 5" /></StackPanel>DataTable dt = new DataTable();dt.Columns.Add("Id", Type.GetType("System.String"));dt.Columns.Add("Name", Type.GetType("System.String"));dt.Columns.Add("Age", Type.GetType("System.String"));
dt.Rows.Add(new object[] { "1", "Tim", "29" });dt.Rows.Add(new object[] { "2", "Tom", "28" });dt.Rows.Add(new object[] { "3", "Tony", "27" });dt.Rows.Add(new object[] { "4", "Kyle", "26" });
this.listBoxStudents.ItemsSource = dt.DefaultView;this.listBoxStudents.DisplayMemberPath = "Name";

<StackPanel x:Name="stackPanel" Background="LightBlue" > <ListView x:Name="listViewStudents" Height=" 110" Margin="5" > <ListView.View> <GridView> <GridViewColumn Header="ID" Width="60" DisplayMemberBinding="{Binding Id}" /> <GridViewColumn Header="Name" Width="80" DisplayMemberBinding="{Binding Name}" /> <GridViewColumn Header="Age" Width="60" DisplayMemberBinding="{Binding Age}" /> </GridView> </ListView.View> </ListView></StackPanel>this.listViewStudents.DataContext = dt;this.listViewStudents.SetBinding(ListView.ItemsSourceProperty, new Binding());<?xml version="1.0" encoding="utf-8" ?> //RawData.xml<StudentList> <Student Id="1"> <Name>Tim</Name> </Student> <Student Id="2"> <Name>Tom</Name> </Student> <Student Id="3"> <Name>Vina</Name> </Student> <Student Id="4"> <Name>Emily</Name> </Student></StudentList><StackPanel x:Name="stackPanel" Background="LightBlue" > <ListView x:Name="listViewStudents" Height=" 110" Margin=" 5" > <ListView.View> <GridView > //加@表示屬性,不加@表示子級元素 <GridViewColumn Header="ID" Width="60" DisplayMemberBinding="{Binding XPath=@Id}" /> <GridViewColumn Header="Name" Width="80" DisplayMemberBinding="{Binding XPath=Name}" /> </GridView> </ListView.View> </ListView></StackPanel>//方法1 //XmlDocument doc = new XmlDocument();//doc.Load(@"D:\RawData.xml");//XmlDataProvider xdp = new XmlDataProvider();//xdp.Document = doc;//xdp.XPath = @"/StudentList/Student"; //使用Xpath選擇需要暴露的數據
//方法2XmlDataProvider xdp = new XmlDataProvider();xdp.Source = new Uri(@"D:\RawData.xml");xdp.XPath = @"/StudentList/Student";
this.listViewStudents.DataContext = xdp;this.listViewStudents.SetBinding(ListView.ItemsSourceProperty, new Binding());
List<Student> stuList = new List<Student>(){ new Student() { Id=0, Name="Tim", Age=29 }, new Student() { Id=1, Name="Tom", Age=28 }, new Student() { Id=2, Name="Kyle", Age=27 }, new Student() { Id=3, Name="Tony", Age=26 }, new Student() { Id=4, Name="Vina", Age=25 }, new Student() { Id=5, Name="Mike", Age=24 },};
this.listViewStudents.ItemsSource = from stu in stuList where stu.Name.StartsWith("T") select stu;//數據在XMLthis.listViewStudents.ItemsSource = from element in xdoc.Descendants("Student") where element.Attribute("Name").Value.StartsWith("T") select new Student() { Id = int.Parse(element.Attribute("Id").Value), Name = element.Attribute("Name").Value, Age = int.Parse(element.Attribute("Age").Value) };<StackPanel Background="LightBlue" > <TextBox x:Name="textBoxArg1" Margin="5"></TextBox> <TextBox x:Name="textBoxArg2" Margin="5"></TextBox> <TextBox x:Name="textBoxResult" Margin="5"></TextBox></StackPanel>//創(chuàng )建并配置ObjectDataProvider對象ObjectDataProvider odp = new ObjectDataProvider(); odp.ObjectInstance = new Calculator();odp.MethodName = "Add";odp.MethodParameters.Add("0");odp.MethodParameters.Add("0");
//以ObjectDataProvider對象為Source創(chuàng )建Binding Binding bindingToArg1 = new Binding("MethodParameters[0]"){ Source = odp, BindsDirectlyToSource = true, //把UI接收到的數據寫(xiě)入其直接Source(即ObjectDataProvider)而不是Calculator對象 UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged //有更新立刻將值傳回Source};
Binding bindingToArg2 = new Binding("MethodParameters[1]"){ Source = odp, BindsDirectlyToSource = true, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged};//把ObjectDataProvider對象當做Source時(shí),這個(gè)對象本身就是數據,所以Path可以省略用.代替Binding bindingToResult = new Binding(".") { Source = odp };
this.textBoxArg1.SetBinding(TextBox.TextProperty, bindingToArg1);this.textBoxArg2.SetBinding(TextBox.TextProperty, bindingToArg2);this.textBoxResult.SetBinding(TextBox.TextProperty, bindingToResult);
<Grid x:Name="g1" Background="Red" Margin="10"> <DockPanel x:Name="d1" Background="Orange" Margin="10"> <Grid x:Name="g2" Background="Yellow" Margin="10"> <DockPanel x:Name="d2" Background="LawnGreen" Margin="10"> <TextBox x:Name="textBox1" FontSize="24" Margin="10" Text="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid},AncestorLevel=1 },Path=Name}"/> </DockPanel> </Grid> </DockPanel></Grid>//TextBox 綁定 等效代碼RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor); //引用元素綁定元素父鏈上級 //rs.AncestorLevel = 1; //以Binding目標控件為起點(diǎn)的層級偏移量 d2是1 g2是2 d1是3 g1是4rs.AncestorType = typeof(Grid); //源的類(lèi)型,不是則跳過(guò)Binding binding = new Binding("Name") { RelativeSource = rs };this.textBox1.SetBinding(TextBox.TextProperty, binding);
//顯示d1Text="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Dockpanel},AncestorLevel=2},Path=Name}"//顯示textBox1RelativeSource rs = new RelativeSource(RelativeSourceMode.Self);Binding binding = new Binding("Name") { RelativeSource = rs };this.textBox1.SetBinding(TextBox.TextProperty, binding); <StackPanel> <TextBox x:Name="textBox1" Margin="5" /> <Slider x:Name="slider1" Minimum="0" Maximum="100" Margin="5" /></StackPanel>public class RangeValidationRule : ValidationRule{ //需要實(shí)現Validate 方法 public override ValidationResult Validate(object value, 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, "Validation Failed"); }}
private void Window_Loaded(object sender, RoutedEventArgs e){ Binding binding = new Binding("Value") { Source = this.slider1 }; binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
RangeValidationRule rvr = new RangeValidationRule(); binding.ValidationRules.Add(rvr);
this.textBox1.SetBinding(TextBox.TextProperty, binding);}
public interface IValueConverter{ object Convert(object vale, Type outputType, object parameter, CultureInfo cultrue); object ConvertBack(object value, Type outputType, object parameter, CultureInfo culture);}<Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" Title="MainWindow" Height="266" Width="300" >
<Window.Resources > <local:CategoryToSourceConverter x:Key="cts"/> <local:StateToNullableBoolConverter 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="80,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,0" Click="buttonLoad_Click" /> <Button x:Name="buttonSave" Content="Save" Height="25" Margin="5,5" Click="buttonSave_Click" /> </StackPanel></Window>using System;using System.Collections.Generic;using System.Text;using System.Windows;using System.Windows.Data;using System.Globalization;using System.IO;
namespace WpfApp1{ public enum Category { Bomber, Fighter }
public enum State { Available, Locked, Unknown }
public class Plane { public Category Category { get; set; } public string Name { get; set; } public State State { get; set; } } /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); }
private void buttonLoad_Click(object sender, RoutedEventArgs e) { List<Plane> planeList = new List<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()); } }
public class CategoryToSourceConverter:IValueConverter { public object Convert(object value,Type targerType,object parameter,CultureInfo cultrue) { Category c = (Category)value; switch (c) { case Category.Bomber: return @"\Bomber.png"; case Category.Fighter: return @"\Fighter.png"; default: return null; } } //不會(huì )被調用 public object ConvertBack(object value, Type targetType,object parameter,CultureInfo culture) { throw new NotImplementedException(); } }
public class StateToNullableBoolConverter:IValueConverter { //將State轉換為bool? public object Convert(object value,Type targetType,object parameter,CultureInfo culture) { State s = (State)value; switch(s) { case State.Locked: return false; case State.Available: return true; case State.Unknown: default: return null; } } //將bool?轉換為State 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; } } }}



聯(lián)系客服